0

i don't understand well how to use the merge statement, i need to translate the following into the equivalent merge statement. Is merge faster then update/insert?

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
Devart
  • 119,203
  • 23
  • 166
  • 186
sparrows81
  • 431
  • 3
  • 6
  • 19

1 Answers1

1

Try this one -

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);
Devart
  • 119,203
  • 23
  • 166
  • 186