patternsqlMinor
Should I set a variable in the same line in which it was declared?
Viewed 0 times
samethelinedeclaredwasshouldwhichvariableset
Problem
I frequently see the syntax
But you can set the variable at declaration time
Is there a gotcha to the latter option? Am I missing something that is internal or doesn't work in all cases where you should not declare and set the variable in the declaration?
I ask because of subtitle gotcha's that I hear which I would not expect. Like Aaron Bertrand lower casing data types which is something that msdn also does not state but has been found in the community.
Declare @var int;
Set @var = 1;But you can set the variable at declaration time
Declare @var int = 1;Is there a gotcha to the latter option? Am I missing something that is internal or doesn't work in all cases where you should not declare and set the variable in the declaration?
I ask because of subtitle gotcha's that I hear which I would not expect. Like Aaron Bertrand lower casing data types which is something that msdn also does not state but has been found in the community.
Solution
It was not possible until SQL Server 2008. Before this version you should declare the variable, and then set its value.
According MS DOCS:
THIS TOPIC APPLIES TO:
SQL Server (starting with 2008)
Azure SQL Database
Azure SQL Data Warehouse
Parallel Data Warehouse
According MS DOCS:
THIS TOPIC APPLIES TO:
SQL Server (starting with 2008)
Azure SQL Database
Azure SQL Data Warehouse
Parallel Data Warehouse
Context
StackExchange Database Administrators Q#164950, answer score: 2
Revisions (0)
No revisions yet.