Be careful: unlike most other languages, T-SQL does not limit variables' scope to the block where the variable has been defined. For example, the following snippet compiles and runs:
-- @to is not in scope yet
-- the line below would not compile
--SET @to = @to + 3 ;
IF DATEPART(weekday, GETDATE()) = 3
BEGIN ;
-- the scope of this DECLARE does not end when the block ends
DECLARE @from INT ,
@to INT ;
SELECT @from = 5 ,
@to = 7 ;
SELECT Number
FROM data.Numbers
WHERE Number BETWEEN @from AND @to ;
-- both @from and @to are defined beyond this point
END
ELSE
BEGIN ;
-- Big surprise:
-- @from and @to are still in scope, this compiles and runs
SET @to = @to + 3 ;
SELECT Number
FROM data.Numbers
WHERE Number BETWEEN @from AND @to ;
END ;
This is counter-intuitive for most developers that worked with other languages. IMO this is one of those features we would probably be better off without. What do you think?
Comment Notification
If you would like to receive an email when updates are made to this post, please register here
Subscribe to this post's comments using
About Alexander Kuznetsov
Alex Kuznetsov has been working with object oriented languages, mostly C# and C++, as well as with databases for more than a decade. He has worked with Sybase, SQL Server, Oracle and DB2. He regularly blogs on sqlblog.com, mostly about database unit testing, defensive programming, and query optimization.
Alex has written a book entitled "Defensive Database Programming with Transact-SQL" and several articles on simple-talk.com and devx.com. Currently he works at DRW Trading Group in Chicago, where he leads a team of developers, practicing agile development, defensive programming, TDD, and database unit testing.