How to assign a column value to a variable name?

minh tran 76 Reputation points
2021-11-09T21:50:29.217+00:00

Hello,
I am new to Transaction query, and I want to learn it.
I am trying to assign a last column value on a table to a variable and it worked if I try my simple sql statement below :

declare @location nvarchar(50);

select @location = location FROM dbo.productcategory order by ProductCategoryID desc;
print @location

However, it does not work in the new sql statement below and it gave me an error such as "Must declare the scalar variable "@alenzi ". which I already declare below. Does anybody know what I did wrong?

declare @location nvarchar(50);
declare @alenzi nvarchar(50);

set @alenzi = N'select @location' + ' = location FROM dbo.productcategory order by ProductCategoryID desc'

exec sys.sp_executesql @alenzi ;

print @location

Thank you,
Du

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

9 answers

Sort by: Most helpful
  1. minh tran 76 Reputation points
    2021-11-12T15:09:56.163+00:00

    Thank you so much ALL for all of the help. I tried different ways of executesql and it works perfectly. Those include embedded a value into the string and I tried to pass a parameter value into the string. Both ways works.

    Please suggest what I should do next regarding my learning of dynamic sql. I have some experienced with python, java and I use regex quite a bit. Could I embed a regeex expression into a query string and makes it search for all possible values ?

    Thanks for all of the helps.
    Du


  2. minh tran 76 Reputation points
    2021-11-13T12:03:18.347+00:00

    Thank you so much for all of the help. I am going to follow your advice.
    Regards,
    Du

    0 comments No comments

  3. Erland Sommarskog 101.8K Reputation points MVP
    2021-11-13T12:28:54.553+00:00

    In case you find my article too much to swallow at a time, or you prefer a different format, I strongly recommend watching Kenneth Fisher's presentation Demystifying Dynamic SQL from PASS last year: https://www.youtube.com/watch?v=CMr_PLiXzUw&list=PLoGAcXKPcRva915OeutOXOtFKN19WSL4I&index=170.

    0 comments No comments

  4. minh tran 76 Reputation points
    2021-11-13T13:59:13.663+00:00

    Thank you so much for recommendations. I am going to watch the supplementary tutorial as well.
    Regards,
    Du

    0 comments No comments