Recently made a report in which stored procedures, cursors, CTE expressions, temporal tables, and table variables are used in the report.
The problem comes when the cursor iterates through the data in the CTE, stores the corresponding data in the variable, inserts the variable into the table variable, and after the cursor ends, wants to filter the table variable based on the parameters of the stored procedure.
When a SQL statement is stitched with dynamic SQL, an error occurs. A table variable is not declared when prompted.
In fact, table variables cannot be used in dynamic SQL. What do we do? I'm inserting data from a table variable into a temporary table, and then stitching it up with a utility temporary table in dynamic SQL.
I don't know if we have any better ideas.
Note:
Temp table:
#tablename
Table variables
DECLARE @tablename TABLE ( .....)
In the SQL splicing, stitching conditions have a certain special wording
DECLARE @sql NVARCHAR (Max) DECLARE @cloum NVARCHAR () SET @sql = ' select * FROM table WHERE Condition column = ' + " '" + @cloum + " '"
SQL Server 2008 Table Variable temp table