问题
This is my very first T-SQL question, so I hope I'm not using the wrong terminology. I just learned some basic stored procedures and variable declaration, however there is something I haven't understood.
DECLARE @CurrentDate DATETIME
SET @CurrentDate = GETDATE()
select @CurrentDate
-----------------------
2013-09-25 18:47:07.547
(1 row(s) affected)
If I running the above in two batches ( declare and set together, select after) I get:
DECLARE @CurrentDate DATETIME
SET @CurrentDate = GETDATE()
Command(s) completed successfully.
select @CurrentDate
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@CurrentDate".
It must probably be simple but I couldn't find a solution...
回答1:
You can't run these in separate batches, sorry. Variables are scoped to the batch. You shouldn't have to worry about this inside a stored procedure, since you can't add GO or execute two portions of the code independently, like you can in Management Studio.
来源:https://stackoverflow.com/questions/19011841/local-variable-not-available-after-the-declaration-batch