Local variable not available after the declaration batch

此生再无相见时 提交于 2019-12-25 04:56:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!