带有变量的SQL MERGE

时间:2014-01-28 22:09:28

标签: sql-server tsql merge

如何在Microsoft SQL Server Management Studio 2008 r2中使用@variables的合并功能?

我搜索过的所有示例在线使用表格合并到表格中。变量有可能吗?

例如:

CREATE PROCEDURE UpdateOrder
            @id int,
            @payment_date smalldatetime,
            @amount numeric(10,2)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;



    MERGE order AS o
    USING @id, @payment_date, @amount
    ON @id = o.id
    WHEN MATCHED THEN 
                    UPDATE SET 
                               o.payment_date = @payment_date,
                               o.amount = @amount
                               o.last_updated_on = GETDATE()
    WHEN NOT MATCHED THEN
        INSERT(o.id,o.payment_id,o.amount)
        VALUES(@id,@payment_id,@amount);

这不起作用。谢谢!

2 个答案:

答案 0 :(得分:18)

您可以使用VALUES子句创建单行派生表,其余部分与往常一样。

MERGE order AS o
USING (VALUES (@id,
               @payment_date,
               @amount)) AS s(id, payment_date, amount)
ON s.id = o.id
WHEN MATCHED THEN
  UPDATE SET o.payment_date = s.payment_date,
             o.amount = s.amount,
             o.last_updated_on = GETDATE()
WHEN NOT MATCHED THEN
  INSERT(o.id,
         o.payment_id,
         o.amount)
  VALUES(s.id,
         s.payment_id,
         s.amount); 

您可能也希望阅读Use Caution with SQL Server's MERGE Statement

答案 1 :(得分:8)

或者您可以简单地检查是否存在记录,然后执行更新/插入

IF EXISTS(SELECT * FROM [order] WHERE ID = @id)
 BEGIN
     UPDATE [order]
      SET payment_date = @payment_date,
          amount       = @amount,
          last_updated_on = GETDATE()
     WHERE ID = @id
 END

ELSE 

 BEGIN
   INSERT INTO [order](id,payment_id,amount)
   VALUES(@id,@payment_id,@amount)
 END