Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server select variable where no results

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

like image 736
profimedica Avatar asked Nov 19 '18 16:11

profimedica


People also ask

How do I check if a variable is empty in SQL Server?

The recommended way to check whether a table variable or table is empty is to use the predicate IS_EMPTY.

Why SELECT * is not recommended?

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).

Can we use variable in WHERE clause in SQL?

You can use variables in place of a table name or combine them with the WHERE clause, in place of filter values.

How can you tell if a SELECT returned no rows?

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.


1 Answers

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;
like image 126
Ilyes Avatar answered Oct 03 '22 11:10

Ilyes