MattDionis
MattDionis

Reputation: 3616

Run Select statement in Stored Procedure based on conditional logic

I've recently been simplifying many formally manual processes on SQL Server 2008 into stored procedures. I'm attempting to turn the below multi-step process into a stored procedure with conditional logic, but not sure how to accomplish this.

  1. Run SELECT COUNT(*) FROM vw_GENERIC_VIEW_NAME

  2. Run SELECT COUNT(*) FROM tbl_SIMPLE_TABLE_NAME

  3. Compare results and if they are not equal run a SELECT statement against tbl_SIMPLE_TABLE_NAME to analyze details.

Is there a way to compare the results through some sort of conditional logic and only run the final SELECT statement if they are not equal in a stored procedure on SQL Server?

Upvotes: 0

Views: 230

Answers (2)

Tanner
Tanner

Reputation: 22733

You can just compare the counts from the 2 tables in an IF statement and conditionally execute code within the block if the valued don't match:

IF ( SELECT COUNT(*)
     FROM   vw_GENERIC_VIEW_NAME
   ) != ( SELECT    COUNT(*)
          FROM      tbl_SIMPLE_TABLE_NAME
        )
    BEGIN
        PRINT 'NOT EQUAL - run your code in place of this print statement'
    END

Upvotes: 1

Pரதீப்
Pரதீப்

Reputation: 93694

Use IF statement with <> operator

IF (SELECT COUNT(*) FROM vw_GENERIC_VIEW_NAME) <> (SELECT COUNT(*) FROM tbl_SIMPLE_TABLE_NAME)
BEGIN
Select ... From tbl_SIMPLE_TABLE_NAME
END

Upvotes: 2

Related Questions