如何建立内部CURSOR动态SQL查询(How to create dynamic SQL quer

2019-10-18 02:58发布

我要动态地创建内部查询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

但在执行此抛出一个异常

消息137,级别15,状态2,行1
必须声明标量变量“@hdoc”

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

如果这种说法是公用表表达式,一个XMLNAMESPACES子句或更改跟踪上下文子句,前面的语句
必须以semicolon.`终止

但是,当我执行游标外相同的查询,这是工作的罚款。

Answer 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


Answer 2:

尝试这个 :

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;


Answer 3:

更改

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);')


文章来源: How to create dynamic SQL queries inside CURSOR