I'm currently editing a procedure, let's call it A, that does some manipulations of a temporary table created in procedure B (so procedure B calls A). Procedure B contains one argument, which is the name of the said temporary table.
That being said, we need to retrieve all the columns (in a CSV) of the temporary table into a variable. Since the name is not the same everytime, I need to use dynamic SQL.
Here is what I have:
-- Input parameters: @sTempTableName VARCHAR(MAX) --> Name of the temporary table to alter
DECLARE
@sColumns AS NVARCHAR(MAX) = '',
@sAlterTableDynamicSQL AS VARCHAR(MAX)
SET @sAlterTableDynamicSQL =
'
SELECT @sColumns = @sColumns + [name] + N'','' FROM Tempdb.Sys.Columns WHERE [object_id] = object_id(''tempdb..' + @sTempTableName + ''')
'
PRINT (@sAlterTableDynamicSQL)
EXEC (@sAlterTableDynamicSQL)
This fails saying that I need to declare @sColumns since it does not exists (I guess variables aren't shared between connections). How can I manage to do this ? I figured I could create another temporary table to hold that CSV, but I'm thinking there should be another way.
@sAlterTableDynamicSQLto be after it is set?object_id? Your dynamic SQL doesn't seem to make sense, is there something missing?sp_executesql(which is the best practice way to execute dynamic SQL), you can pass parameters in and out.@sAlterTableDynamicSQLis expected to beSELECT @sColumns = @sColumns + [name] + N',' FROM Tempdb.Sys.Columns WHERE [object_id] = object_id('tempdb..#tempTable'), if the name of the table is#tempTable.@sColumnsshould be the list of the columns, separated by commas (for example, if there are 2 columns, ID and Name, we should have:ID,Name,. MySQL version isSQL Server 2016