How can I declare a variable in T-SQL and use it in multiple statements?
For example:
DECLARE @STRDT DATE
SET @STRDT '2017-01-01'
SELECT TOP(10) *
FROM TABLE1
WHERE START_DATE = @STRDT;
SELECT TOP(10) *
FROM TABLE2
WHERE START_DATE = @STRDT;
Right now, I am able to run the first statement correctly, but unable to use the declared variable in my second statement. I get an e error
Must declare @STRDT
when I am running the second select statement in SQL Server.
3条答案
按热度按时间unftdfkk1#
Variables exist only within a certain scope which is within a statement that is being run. Therefore, when you have logic like this in a stored procedure it'll be run within the same scope because it's the same batch so the variable will "work" for both statements. It's the same thing when you want to run it manually - you have to run both statements together in order to get what you want. That's simply how it works and if you run both statements at the same time - the variable "works" in both - or multiple - statements.
To read up more on them, consult the following sources:
wyyhbhjk2#
As pointed out in the comments, its not working for second statement because of the presence of the semi-colon ;
If you want to use the variable in both statements, remove the semi-colon between the two statements and run the entire code.
xxb16uws3#
The OP does not indicate which client app they're using to execute the SQL statements. Probably SSMS, since that's the usual MS SQL Server tool? Or maybe Azure Data Studio?
In my case, I've been trying to execute such multi-statement batches in DBeaver for MS SQL Server T-SQL. As noted here , you can (sometimes) make this work by surrounding the statements with
BEGIN
andEND
. For example, for the simple query below, you can execute the following usingCtrl+Enter
orCtrl+\
anywhere in theBEGIN
-END
block. It will open two tabs since there are twoSELECT
statements.For more complex queries, it can be necessary to position the cursor on the
BEGIN
statement and then useCtrl+Enter
orCtrl+\
. (Or, alternatively, highlight the entireBEGIN
-END
block and pressAlt+X
.) In particular, I've found this to be necessary when the SQL statement(s) containwith cte1 (...)...
Common Table Expressions.I've also been running into more complex batches of SQL statements that execute successfully in SSMS, but that DBeaver rejects because it complains that there is a syntax error. I have not found a solution to that problem.
Bottom line with respect to DBeaver: it seems it simply won't execute some MS Sql Server T-Sql multi-statement batches that SSMS and Azure Data Studio execute correctly.