1

我必须在里面动态创建一个查询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”

消息 319,级别 15,状态 1,第 1 行
关键字“with”附近的语法不正确。

如果此语句是公用表表达式、xmlnamespaces 子句或更改跟踪上下文子句,则前面的语句
必须以分号结尾。`

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

4

3 回答 3

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
于 2013-05-07T04:34:54.517 回答
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);')
于 2013-05-06T08:22:03.367 回答
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;
于 2013-05-06T08:58:51.117 回答