Set value in variable from dynamic query in SQL

By SP

The following procedure stores the value to the parameter from the dynamic query.

DECLARE @reccount INT
DECLARE @nextcol VARCHAR(MAX)
SET @nextcol = 'Column_Name'
EXEC sp_executesql N'SELECT @reccount=COUNT(*) FROM Talbe_Name WHERE @nextcol is not null',
N'@reccount int OUTPUT, @nextcol varchar(max)', @reccount OUTPUT, @nextcol
PRINT(@reccount)

Hope you find it useful.

Set value in variable from dynamic query in SQL  (965 Views)