将表变量传递给exec SQL Server

时间:2016-10-25 15:08:26

标签: sql sql-server variables exec

我正在尝试编写此存储过程,但是我无法将临时表(或表变量)的结果传递给EXEC (@SQL)任务:

    DECLARE @colsUnpivot AS NVARCHAR(MAX)
    DECLARE @query  AS NVARCHAR(MAX)
    DECLARE @Table_Name as Varchar(200)
    DECLARE @transaction_Table   NVarchar(500)

    SET @Table_Name = 'opd_scholar'
    SET @transaction_Table = 'opd_scholar_transaction'

    --DECLARE @TEMP TABLE(colsUnpivot varchar(max))
    CREATE TABLE #TEMP (colsUnpivot varchar(max))

    SELECT @colsUnpivot = 'SELECT 
  STUFF ( (
            SELECT '', ''+ QUOTENAME(InTab.COLUMN_NAME)
            FROM INFORMATION_SCHEMA.COLUMNS InTab
            WHERE InTab.TABLE_NAME = OutTab.TABLE_NAME
            ORDER BY InTab.ORDINAL_POSITION
            FOR XML PATH(''''), TYPE 
            ).value(''.'',''VARCHAR(MAX)''
         ) , 1,1,SPACE(0))
  FROM INFORMATION_SCHEMA.COLUMNS OutTab
    WHERE TABLE_NAME = '''+ @Table_Name +'''
     GROUP BY OutTab.TABLE_NAME'
   --INSERT INTO @TEMP (colsUnpivot)
   INSERT INTO #TEMP (colsUnpivot)
   EXEC(@colsUnpivot)
   PRINT @colsUnpivot
   --SELECT colsUnpivot FROM @TEMP
   SELECT colsUnpivot FROM #TEMP

   DECLARE @TEMP1 NVARCHAR(MAX) = 'SELECT colsUnpivot FROM #TEMP'

   --PRINT @TEMP

    SET @query 
     = 'INSERT INTO '+ @transaction_Table +' (  unitid,institution,city,state,zip,code_name,lkp_value) 
  SELECT unitid,institution,city,state,zip,code_name,lkp_value
  FROM  
  (
  SELECT unitid,institution,city,state,zip, '+ @TEMP1+'
  FROM '+@Table_name+') AS cp
    UNPIVOT (lkp_value for code_name  IN ('+@TEMP1+')
   ) AS up' 
  PRINT @Query
 --PRINT @Query1
  EXEC(@query)
  DROP TABLE #TEMP

我还使用了表变量(参见注释区域),但不确定这是如何工作的。

请将此代码复制并粘贴到查询窗口中以获得更多理解。 多数民众赞成霍根。我希望@colsUnpivot的结果在某个变量中,这样我就可以将其发送到我目前正在使用@ TEMP1的下一段代码。

1 个答案:

答案 0 :(得分:0)

试试这个

DECLARE @colList VARCHAR(MAX)

SELECT @colList = 
  Stuff((
    Select ', ' + C.COLUMN_NAME
    From INFORMATION_SCHEMA.COLUMNS As C
    Where C.TABLE_SCHEMA = T.TABLE_SCHEMA
        And C.TABLE_NAME = T.TABLE_NAME
    Order By C.ORDINAL_POSITION
    For Xml Path('')
 ), 1, 2, '') 
From INFORMATION_SCHEMA.TABLES As T
WHERE TABLE_NAME = @Table_Name
GROUP BY TABLE_NAME

然后使用@colList代替@TEMP1

你不需要临时表或任何其他疯狂。

(nb - 我从这里得到了列代码https://stackoverflow.com/a/4936669/215752