Try these statements:
set @sql = N'select top(1) @location = location FROM dbo.productcategory order by ProductCategoryID desc'
exec sys.sp_executesql @sql, @params = N'@location nvarchar(50) OUTPUT', @location = @location OUTPUT
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
Try these statements:
set @sql = N'select top(1) @location = location FROM dbo.productcategory order by ProductCategoryID desc'
exec sys.sp_executesql @sql, @params = N'@location nvarchar(50) OUTPUT', @location = @location OUTPUT
Hi @minh tran ,
Welcome to the microsoft TSQL Q&A forum!
The three posts you posted are the same, so I merged them for you.
Please refer to:
declare @location nvarchar(max);
declare @sql nvarchar(max);
set @sql = N'select top(1) @location = location FROM dbo.productcategory order by ProductCategoryID desc'
exec sys.sp_executesql @sql,
N'@location VARCHAR(MAX) OUTPUT',
@location OUTPUT;
print @location;
If you have any question, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.
Regards,
Echo
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".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Thank you so much All for all of the helps. It worked very well!!
I have one question regarding the variable @location from the solution above.
I try to figure it out why does the variable @location need to appear twice on line 1 as
declare @location nvarchar(max);
and again on line 7 as
N'@location VARCHAR(MAX) OUTPUT',
Could I just drop the VARCHAR(MAX) and just have this on line 7 as
N'@location OUTPUT',
Would it work ? and I try to figure out why it did not.
Many thanks for explanation why it would not work!
Thank you so much. I see that the syntax requires that I need to have @Kritivasas name, its data type, and input or output parameter. So it did not work if I simply had @Kritivasas name , and input or output parameter because the data type was missing.