0

I got the following SQL Code, I need

  1. Execute an Insert only if the code returns more than 0 rows.
  2. 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 )

1 Answer 1

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' 
Sign up to request clarification or add additional context in comments.

1 Comment

This should get you pointed in the right direction. I did not touch the insert as I was unsure of what exactly you wanted inserted and where.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.