3

以前从未使用MERGE过,也从未使用过 Sybase ASE 15.7

我需要一个存储过程来更新现有数据,或者如果它不存在则插入它。我知道如何在没有它的情况下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 > 参考手册:命令 > 命令

4

1 回答 1

2

刚刚进行了更改@PeterHenell 评论并醒来。

    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
于 2017-02-15T17:30:41.837 回答