帮助将upsert语句转换为merge语句sql server

时间:2013-07-01 12:28:51

标签: sql-server merge upsert

我不太清楚如何使用merge语句, 我需要将以下内容翻译成等效的合并语句。 合并更快然后更新/插入吗?

ALTER PROCEDURE [dbo].[IOUUS] 

     @a VARCHAR(50),
     @b VARCHAR(50),
     @c NVARCHAR(4000)

AS
BEGIN

     IF EXISTS (
          SELECT c
          FROM T
     )

          UPDATE T
          SET  c = @c
             , d = GETUTCDATE()
          WHERE b = @b AND a = @a

     ELSE

          INSERT INTO T (a, b, c, d)
          VALUES (@a, @b, @c, GETUTCDATE())

END

1 个答案:

答案 0 :(得分:1)

试试这个 -

MERGE dbo.t t
USING (SELECT @a, @b, @c, GETUTCDATE()) s (a, b, c, d)
ON (t.b = s.b AND t.a = s.a)
WHEN MATCHED THEN 
     UPDATE SET 
            c = s.c
          , d = s.d
WHEN NOT MATCHED THEN   
    INSERT (a, b, c, d)
    VALUES (s.a, s.b, s.c, s.d);