Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

sql server 2005 - Local variable not available after the declaration batch

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...