Could two queries share the same parameter/variable?

Jonathan Brotto 420 Reputation points
2024-07-30T20:19:21.79+00:00

Could two queries share the same parameter/variable?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,014 questions
SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
102 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,657 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Erland Sommarskog 112.7K Reputation points MVP
    2024-07-30T20:47:01.5033333+00:00

    Probably.

    (And if you want a more detailed answer, you need to ask a more detailed question.)


  2. LiHongMSFT-4306 28,121 Reputation points
    2024-07-31T01:30:31.61+00:00

    Hi @Jonathan Brotto

    When two queries are in same batch, then it is possible.

    Check this simple sample:

    Declare @ID INT=10001
    
    select * from DemoTable where ID = @ID;
    select * from DemoTable where ID <> @ID;
    

    When the two queries are not in one batch like this:

    Declare @ID INT=10001
    select * from DemoTable where ID = @ID;
    GO
    select * from DemoTable where ID <> @ID;
    

    You might need to declare the parameter again.

    Best regards,

    Cosmog


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.