从sql server中的XML文件中提取XML数据时出错

时间:2016-04-29 05:43:55

标签: sql-server xml

DECLARE @TablesList TABLE 
(
    TableName VARCHAR(500),
    RefTable VARCHAR(500),
    RefTableIDColumn VARCHAR(500)
)
DECLARE @Query AS VARCHAR(MAX)


SET @Query = 'DECLARE @badIds AS VARCHAR(500) DECLARE @TableXML AS XML'
SET @Query = @Query + ' SELECT @TableXML = xCol FROM (SELECT * FROM OPENROWSET (BULK ''\\10.0.0.60\Temp\path\DataItemTables.xml'', SINGLE_CLOB)AS xCol) AS R(xCol)'
SET @Query = @Query + ' INSERT INTO @TablesList SELECT ref.value(''tablename[1]'',''nvarchar(500)'') AS tablename,'
SET @Query = @Query + ' ref.value(''refTable[1]'',''nvarchar(500)'') AS refTable, ref.value(''refTableIDColumn[1]'',''nvarchar(500)'') AS refTableIDColumn FROM'
SET @Query = @Query + ' @TableXML.nodes(''//Table[@name="Description"]'') AS R(ref)'
SET @Query = @Query +'select * from @TablesList'

EXEC(@Query)

我正在执行上面的脚本。但我收到如下错误

Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "@TablesList".
Msg 1087, Level 15, State 2, Line 1
Must declare the table variable "@TablesList".

我做错了什么。但是,当我以动态形式编写查询时,如下所示,它工作正常。问题是我想删除SP的所有动态部分。

DECLARE @Query AS VARCHAR(MAX)

SET @Query ='DECLARE @TablesList TABLE ( TableName VARCHAR(500),RefTable VARCHAR(500),RefTableIDColumn VARCHAR(500))'
SET @Query = @Query + ' DECLARE @badIds AS VARCHAR(500) DECLARE @TableXML AS XML'
SET @Query = @Query + ' SELECT @TableXML = xCol FROM (SELECT * FROM OPENROWSET (BULK ''\\10.0.0.60\Temp\Path\DataItemTables.xml'', SINGLE_CLOB)AS xCol) AS R(xCol)'
SET @Query = @Query + ' INSERT INTO @TablesList SELECT ref.value(''tablename[1]'',''nvarchar(500)'') AS tablename,'
SET @Query = @Query + ' ref.value(''refTable[1]'',''nvarchar(500)'') AS refTable, ref.value(''refTableIDColumn[1]'',''nvarchar(500)'') AS refTableIDColumn FROM'
SET @Query = @Query + ' @TableXML.nodes(''//Table[@name="Description"]'') AS R(ref)'
SET @Query = @Query +'select * from @TablesList'

EXEC(@Query)

1 个答案:

答案 0 :(得分:4)

您只能访问声明它的同一范围内的表变量。由于EXEC的范围不同,因此无法识别表变量。解决此问题的一种方法是使用临时表:

CREATE TABLE #TablesList
(
    TableName VARCHAR(500),
    RefTable VARCHAR(500),
    RefTableIDColumn VARCHAR(500)
)
DECLARE @Query AS VARCHAR(MAX)

SET @Query = 'DECLARE @badIds AS VARCHAR(500) DECLARE @TableXML AS XML'
SET @Query = @Query + ' SELECT @TableXML = xCol FROM (SELECT * FROM OPENROWSET (BULK ''\\10.0.0.60\Temp\path\DataItemTables.xml'', SINGLE_CLOB)AS xCol) AS R(xCol)'
SET @Query = @Query + ' INSERT INTO #TablesList SELECT ref.value(''tablename[1]'',''nvarchar(500)'') AS tablename,'
SET @Query = @Query + ' ref.value(''refTable[1]'',''nvarchar(500)'') AS refTable, ref.value(''refTableIDColumn[1]'',''nvarchar(500)'') AS refTableIDColumn FROM'
SET @Query = @Query + ' @TableXML.nodes(''//Table[@name="Description"]'') AS R(ref)'
SET @Query = @Query +'select * from #TablesList'

EXEC(@Query)