Can anyone point out how to check if a select query returns non empty result set?
For example I have next query:
SELECT * FROM service s WHERE s.service_id = ?;
Should I do something like next:
ISNULL(SELECT * FROM service s WHERE s.service_id = ?)
to test if result set is not empty?
You can use @@ROWCOUNT. For e.g. You will get 0 if first statement will not return any rows. You can also use if statement to check that just after first statement.
Of course it returns 1! If there is a row being returned it doesn't matter what the row's columns look like. A column with null value can be valuable information.
The IS NULL condition is used in SQL to test for a NULL value. It returns TRUE if a NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.
IF EXISTS(SELECT * FROM service s WHERE s.service_id = ?) BEGIN --DO STUFF HERE END
Use @@ROWCOUNT:
SELECT * FROM service s WHERE s.service_id = ?; IF @@ROWCOUNT > 0 -- do stuff here.....
According to SQL Server Books Online:
Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With