Warm tip: This article is reproduced from serverfault.com, please click

Set @Variable1 within a stored proc by executing @Variable2

发布于 2020-11-25 21:57:22

I want to set the value of @Count by executing @Counter within a Begin Try of a stored procedure.

SET @Counter ='SET @Count = (SELECT COUNT(' + @COLUMN + ') FROM ' + @TABLE + ' WHERE CONVERT(VARCHAR(MAX),' + @COLUMN + ') = ''' + @DATATOFIND + ''')'

I have tested the above code and it does give me the expected result for populating the @Count variable inside of a normal sql statement outside of a stored procedure.

Once the @Count variable is populated I want to use it in a print statement.

PRINT '-- No. of Entries in the ' + @TABLE + ' Table = ' + @Count

I have tried to the following two options to get the @Count populated but neither has worked

EXEC @Counter

and

EXECUTE sp_executesql (@Counter)

UPDATE:

After some more research I tried this:

DECLARE @Counter NVARCHAR(1000)
SET @Counter = N'DECLARE @Count NVARCHAR(100); SET @COUNT = (SELECT COUNT(UserId) FROM UserGrp WHERE CONVERT(VARCHAR(MAX),UserId) = ''za02'')'
EXECUTE sp_executesql @Counter
Print @Count

But I receive this error: Must declare the scalar variable "@Count"

UPDATE: Workaround / Solution to my situation

DECLARE @Counter NVARCHAR(2000)
SET @Counter = 'DECLARE @Count NVARCHAR(100); SET @COUNT = (SELECT COUNT(UserId) FROM UserGrp WHERE CONVERT(VARCHAR(MAX),UserId) = 'to01'); Print '/*  No. of Entries in the UserGrp Table - ' + @Count + ' */''
EXEC (@Counter)

This gives me clear information in my result to decide what to do with the created code from the rest of the stored proc

Questioner
zucchini
Viewed
0
Lukasz Szozda 2020-11-29 01:15:43

Dynamic SQL requires careful handling:

DECLARE @Counter NVARCHAR(1000);

DECLARE @COUNT BIGINT;
DECLARE @DATATOFIND VARCHAR(100) = 'za02';
DECLARE @TABLE SYSNAME = N'UserGrp';
DECLARE @COLUMN SYSNAME = N'UserId';

SET @Counter = N'SELECT @COUNT = COUNT(<column_name>) 
FROM <table_name> 
WHERE CONVERT(VARCHAR(MAX),<column_name>) = @DATATOFIND;';

SET @Counter = REPLACE(@Counter, '<column_name>', QUOTENAME(@COLUMN));
SET @Counter = REPLACE(@Counter, '<table_name>', QUOTENAME(@TABLE));

PRINT @Counter; -- debug

EXECUTE sp_executesql @Counter, 
       N'@DATATOFIND VARCHAR(100), @COUNT BIGINT OUTPUT',
       @DATATOFIND,
       @COUNT OUTPUT;

SELECT @COUNT;

db<>fiddle demo

Minimum:

  • params are parameters, not concatenated string
  • identifiers(here column/table name) - should be quoted for instance using QUOTENAME function
  • it is good to print query to see if it doing what is expected
  • parameters set inside dynamic query could be passed to outer block by defining them as OUTPUT