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
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;
Minimum:
QUOTENAME
function