Reputation: 3616
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.
Run SELECT COUNT(*) FROM vw_GENERIC_VIEW_NAME
Run SELECT COUNT(*) FROM tbl_SIMPLE_TABLE_NAME
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
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
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