如何检查是否有行并执行插入

时间:2011-08-25 08:13:07

标签: sql tsql

我得到了以下SQL代码,我需要

  1. 仅当代码返回的行数超过0行时才执行Insert。
  2. 将消息放在屏幕上,供执行脚本的人说 没有检测到丢失的行或 检测到并添加了3个缺失的行。

    从DistributionKey_Section中选择*,其中SectionID 不在 (     从站点中选择siteid SiteTypeCodeID IN(8) ) 和DistributionKeyID不在 (     从DistributionKey中选择DistributionKeyID,其中UnitInclusive = 1 )

1 个答案:

答案 0 :(得分:1)

DECLARE
   @MissingRows int,
   @InsertedRows int    

SELECT *
FROM DistributionKey_Section
WHERE SectionID NOT IN ( select siteid from Site where SiteTypeCodeID IN(8) ) AND
      DistributionKeyID NOT IN ( SELECT DistributionKeyID FROM DistributionKey WHERE   
      UnitInclusive=1 )

SET @MissingRows = @@ROWCOUNT     

IF @MissingRows > 0
   BEGIN
   <Insert Statement/Logic>
   SET @InsertedRows = @@ROWCOUNT
   PRINT CAST(@InsertedRows as varchar(5)) + ' missing rows were detected and added'
   IF @MissingRows <> @InsertedRows 
      BEGIN
      RAISERROR('The number of rows inserted does not equal the number of rows missing', 16, 1)
      END
   END
ELSE
   PRINT 'No Missing Rows Detected'