如何在CURSOR中创建动态SQL查询

时间:2013-05-06 08:19:52

标签: sql-server sql-server-2008 tsql sql-server-2008-r2

我必须在cursor

中动态创建查询
DECLARE @id VARCHAR(10)

declare @loc varchar(25)
set @loc = '/MainItem/SubItem';

declare @query varchar(max)     

DECLARE myCursor CURSOR LOCAL FAST_FORWARD FOR
    SELECT * FROM @tempcolumnname

OPEN myCursor
FETCH NEXT FROM myCursor INTO @id

WHILE @@FETCH_STATUS = 0 
BEGIN
    set @query = 'SELECT * FROM OPENXML(@hdoc, '+@loc+', 3) WITH (code_db_key int)'
    exec (@query)    

    FETCH NEXT FROM myCursor INTO @id
END

但执行此操作会抛出异常

  

Msg 137,Level 15,State 2,Line 1
  必须声明标量变量“@hdoc”

     

Msg 319,Level 15,State 1,Line 1
  关键字'with'附近的语法不正确。

     

如果此语句是公用表表达式,则为xmlnamespaces子句   或更改跟踪上下文子句,前一个语句
  必须以分号结束。

但是当我在光标外执行相同的查询时,它工作正常。

3 个答案:

答案 0 :(得分:1)

在游标中,您必须再次执行xml文件,并使用xml输出声明。

DECLARE @id VARCHAR(25)

declare @loc varchar(25)
set @loc = '/MainItem/SubItem';

declare @query varchar(max) 

DECLARE myCursor CURSOR LOCAL FAST_FORWARD FOR
     SELECT * FROM @tempcolumnname

OPEN myCursor
FETCH NEXT FROM myCursor INTO @id

WHILE @@FETCH_STATUS = 0 
BEGIN
    set @query = 'DECLARE @hdoc INT;           
    EXEC sp_xml_preparedocument @hdoc OUTPUT,'''+ @info+'''
        Select Statement
        Insert Statement exec (@query)      

    FETCH NEXT FROM myCursor INTO @id       
END

CLOSE myCursor
DEALLOCATE myCursor

答案 1 :(得分:0)

更改

set @query = 'SELECT * FROM OPENXML(@hdoc, '+@loc+', 3) WITH (code_db_key int)'

set @query = 'SELECT * FROM OPENXML(@hdoc, '+@loc+', 3) WITH (code_db_key int);'

-

好的,试试这个,

set @query = CONCAT('SELECT * FROM OPENXML(@hdoc,',+@loc+,', 3) WITH (code_db_key int);')

答案 2 :(得分:0)

试试这个:

DECLARE @ParmDefinition nvarchar(500);

/* Build the SQL string one time.*/
set @query = 
'SELECT * FROM OPENXML(@Temphdoc, '''+@loc+''', 3) WITH (code_db_key int)';
SET @ParmDefinition = N'@Temphdoc varchar(1000)';

/* This can be in cursor loop */

EXECUTE sp_executesql @query, @ParmDefinition,
                      @Temphdoc = @hdoc;