Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is already declared (T-SQL)?

Tags:

tsql

When I write

DECLARE @x INT

Is there a way to check whether the variable @x has already been declared or not?

like image 532
Dmitrii Avatar asked Apr 04 '11 16:04

Dmitrii


People also ask

How do you check if record already exists in SQL?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do you select a declared variable in SQL?

SELECT @local_variable is typically used to return a single value into the variable. However, when expression is the name of a column, it can return multiple values. If the SELECT statement returns more than one value, the variable is assigned the last value that is returned.

What is @@ variable in SQL?

In SQL Server, symbol @@ is prefixed to global variables. The server maintains all the global variables.

Is != Valid in SQL?

There is no != operator according to the ANSI/SQL 92 standard.


1 Answers

No.
The declaration of variables in tsql does not follow the code path and use scope like perhaps other languages does.

This code shows that @xx exists but is unassigned even though the declaration was never executed.

if 1 = 0 
begin
  declare @xx int = 10
end
else
begin
  declare @yy int = 20
end

print coalesce(@xx, -100)
print coalesce(@yy, -200)

Result

-100
20
like image 196
Mikael Eriksson Avatar answered Sep 22 '22 15:09

Mikael Eriksson