SQL合并中的打印语句

时间:2014-09-04 15:20:55

标签: sql-server

我被要求在SQL合并中包含一些调试PRINT语句,我刚接触过。我被告知OUTPUT并不令人满意。

MERGE Production.UnitMeasure AS target
    USING (SELECT @UnitMeasureCode, @Name) AS source (UnitMeasureCode, Name)
    ON (target.UnitMeasureCode = source.UnitMeasureCode)
    WHEN MATCHED THEN 
        UPDATE SET Name = source.Name
        PRINT "Updated"
    WHEN NOT MATCHED THEN
        INSERT (UnitMeasureCode, Name)
        VALUES (source.UnitMeasureCode, source.Name)
        PRINT "Inserted"

这不起作用,因为每个条件块应该包含一个SQL命令。

有没有一种简单的方法来实现我之后的目标?

1 个答案:

答案 0 :(得分:0)

IF EXISTS (SELECT 1 FROM Production.UnitMeasure  WHERE UnitMeasureCode = @UnitMeasureCode)
  BEGIN
     UPDATE Production.UnitMeasure
        SET Name = @Name
     WHERE  UnitMeasureCode = @UnitMeasureCode
     PRINT 'Updated'
  END
ELSE
  BEGIN
     INSERT Production.UnitMeasure (UnitMeasureCode, Name)
     VALUES (@UnitMeasureCode, @Name)
     PRINT 'Inserted'
  END

或者另一种方法可能是

     UPDATE Production.UnitMeasure
        SET Name = @Name
     WHERE  UnitMeasureCode = @UnitMeasureCode

 IF (@@ROWCOUNT <> 0)
  BEGIN
     PRINT 'Updated'
  END
ELSE  
  BEGIN
     INSERT Production.UnitMeasure (UnitMeasureCode, Name)
     VALUES (@UnitMeasureCode, @Name)
     PRINT 'Inserted'
  END