使用XML数据的Openquery:'<'附近的语法不正确

时间:2014-04-02 09:21:11

标签: sql sql-server sql-server-2012 openquery

我有这段代码:

DECLARE @xml_var XML
SET @xml_var = 
(
    SELECT ID_CODE AS '@ProductionId',
        CODE AS '@ItemId',
        CODE_LEVEL AS '@ItemPackagingLevelId',
        COMMISIONING_FLAG AS '@ItemFlag',
        TIMESPAN AS '@TimeStamp',
        USERNAME AS '@Username',
        SOURCE AS '@Source'
        FROM TRZIC.dbo.CODES_TEMP
    FOR XML PATH('Item'),
    ROOT('Commissioning')
)

DECLARE @xml_str NVARCHAR(MAX) = CONVERT(NVARCHAR(MAX), @xml_var)

 DECLARE @SqlCommand NVARCHAR(MAX) = N'SELECT *
 FROM OPENQUERY([UIC160\SQLEXPRESS],''EXEC TRZIC.dbo.AddCommissioning @data = ''' + @xml_str +''')'

-- DEBUG
PRINT @SqlCommand

EXEC sp_ExecuteSQL @SqlCommand;

PRINT @SqlCommand out的一部分是:

SELECT *
 FROM OPENQUERY([UIC160\SQLEXPRESS],'EXEC TRZIC.dbo.AddCommissioning @data = '<Commissioning><

而且,在EXEC sp_ExecuteSQL @SqlCommand;我得到:

Incorrect syntax near '<'

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如何不使用openquery,而是将值转换为nvarchar(max)并将其用作远程存储过程的参数?

DECLARE @var nvarchar(max);
SET @var = cast(@xml_var as nvarchar(max));

EXEC [UIC160\SQLEXPRESS].TRZIC.dbo.AddCommissioning @var;