Can I set variables if the query returns no results?
DECLARE @Output AS VARCHAR(MAX);
SELECT @Output = 'Old';
SELECT @Output = 'New' WHERE 0 = 1;
PRINT @Output;
Output value is: Old
Expected value is: NULL
The recommended way to check whether a table variable or table is empty is to use the predicate IS_EMPTY.
Avoid using SELECT * There are many reasons for that recommendation, like: SELECT * Retrieves unnecessary data besides that it may increase the network traffic used for your queries. When you SELECT *, it is possible to retrieve two columns of the same name from two different tables (when using JOINS for example).
You can use variables in place of a table name or combine them with the WHERE clause, in place of filter values.
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.
DECLARE @Output AS VARCHAR(MAX);
SELECT @Output = 'Old';
SELECT @Output = 'New' WHERE 0 = 1;
PRINT @Output;
You get 'Old'
cause the variable already has this value, and it will not update the value since in the WHERE
clause you use the condition 0=1
, which will return FALSE
and the value in the variable won't change.
WHERE 0 = 1
It will be False
WHERE 0 <> 1
It will be True
It's just similar to IF 0=1 THEN UpdateMyVar
So in your case the value will always 'Old'
, it won't return 'New'
or NULL
either.
I don't know what are you trying to do really, but if you want to return NULL
then
DECLARE @Output AS VARCHAR(MAX);
SELECT @Output = 'Old';
SELECT @Output = NULL WHERE 0 <> 1; --If 0<> 1 then update my var and set NULL else leave it as it is
PRINT @Output;
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