How to check if there are rows and execute an Insert
I got the following SQL Code, I need
- Execute an Insert only if the code returns more than 0 rows.
Put messages on the screen for the person who executes the script, saying No missing rows were detected or 3 missing rows were detected and added.
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 )
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'
精彩评论