How to Run Another Query if the first query does not Fetch results in SQL SERVER

Lets say you want to keep a back up query which should execute only when the first query does not return any results, then here's how to do so:

I have using the 'Customers' table from the Northwind database in this example


SELECT CompanyName, ContactName, ContactTitle FROM Customers


where CustomerID='XYZ'


-- Check if the first query returned results


-- If the ROWCOUNT is zero, run the other query


if @@ROWCOUNT = 0


BEGIN


SELECT CompanyName, ContactName, ContactTitle FROM Customers


where CustomerID='ALFKI'


END


No comments:

Post a Comment