2017-02-15 2 views
3

で変数を使用して、挿入、更新、私は、既存のデータを更新するか、それが存在しない場合は、それを挿入するためのストアドプロシージャを必要とする前にも、Sybase ASEの15.7SQLマージ。そうでない場合は終了するが、ストアドプロシージャ

MERGEを使用しないでください。 私はMERGEなしでそれを行う方法を知っていますが、私はそれを使用する方法を学びたいと思います。

これは私のテーブルとテストデータです:

CREATE TABLE myTable(
    col1 Smallint Not NULL, 
    col2 Char(15) Not NULL, 
    col3 Char(2)  Not NULL, 
    col4 BIT Not NULL, 
    col5 varchar(100) NULL, 
    Constraint PK_myTable primary key clustered (col1,col2,col3) 
) 
go 

insert into myTable values(1,'A','1',1,'A') 
go 

マイ手順

create procedure spInsertUpdateMytable(
     @col1 Smallint, 
     @col2 Char(15), 
     @col3 Char(2), 
     @col4 BIT, 
     @col5 varchar(100)) 
    AS 

    merge into myTable as V 
     using (select col1, col2, col3, col4, col5 from myTable 
       where @col1=col1 and @col2 = col2 and @col3=col3) as N 
     ON v.col1=n.col1 and v.col2=n.col2 and v.col3=n.col3 
     when not matched then 
      insert (col1, col2, col3, col4, col5) 
      values(@col1, @col2, @col3, @col4, @col5) 
     when matched 
      then update set 
       v.col4 = @col4, v.col5 = @col5 
go 

更新が動作しているようですが、挿入はしていません。私は私が間違ってやって実現することはできません

exec spInsertUpdateMytable 1,'A','1',0,'B' --Update is done ok. 

exec spInsertUpdateMytable 1,'C','1',0,'Z' --No new record added 

、私はこの仕様に Adaptive Server Enterprise 15.7 > Reference Manual: Commands > Commands

+1

私はこの問題が「使用中」のフィルタにあると考えています。行が見つからないため、一致しない行はありません。 –

+1

本質的に、 'using'節は挿入または更新される行を返す必要があります。 'on'節は、行が'マッチする 'か'マッチしない 'かを決定する要素になります。 –

+0

@PeterHenellは大変感謝しています。私は穴のことを理解していない。 – Horaciux

答えて

2

を以下のよただ、変更はコメント@PeterHenell、それはwokedました。

create procedure spInsertUpdateMytable(
     @col1 Smallint, 
     @col2 Char(15), 
     @col3 Char(2), 
     @col4 BIT, 
     @col5 varchar(100)) 
    AS 

    merge into myTable as V 
     using (select @col1 col1, @col2 col2, @col3 col3, @col4 col4, @col5 col5) as N 

     when not matched then 
      insert (col1, col2, col3, col4, col5) 
      values(@col1, @col2, @col3, @col4, @col5) 
     when matched 
      then update set 
       v.col4 = @col4, v.col5 = @col5 
go 
関連する問題