无法找出sql字符串的正确引号结构

时间:2019-09-16 13:15:13

标签: sql-server tsql

我正在尝试将OPENQUERY与动态变量一起使用。我试图创建这样的查询字符串;

DECLARE @SQL nvarchar(MAX);
DECLARE @CRLF nchar(2) = NCHAR(13) + NCHAR(10);

SET @SQL = N'{SELECT * INTO #tmpTable}' + @CRLF +
               N'FROM OPENQUERY("my_source_ip", ''EXEC [DB].dbo.SP_inventory' +  CONVERT(varchar(10),@StoreId) + ',' + QUOTENAME(CONVERT(varchar,@StartDate,112)) + ',' +  QUOTENAME(CONVERT(varchar,@EndDate,112)) +')';

但是,我遇到了以下错误;

Msg 102, Level 15, State 1, Line 7
Incorrect syntax near '{'.
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near '}'.
Msg 105, Level 15, State 1, Line 8
Unclosed quotation mark after the character string 'EXEC [DB].dbo.SP_inventory8005,[20170101],[20190707]'.

如何解决此查询字符串以使其正常工作?谢谢。

1 个答案:

答案 0 :(得分:0)

在存储过程名称之后,您还有一个额外的“,”。我已将其替换为空白。请尝试这个。

DECLARE @SQL nvarchar(MAX);
DECLARE @CRLF nchar(2) = NCHAR(13) + NCHAR(10);

SET @SQL = N'{SELECT * INTO #tmpTable}' + @CRLF +
           N'FROM OPENQUERY("my_source_ip", ''EXEC [DB].dbo.SP_inventory' +  
CONVERT(varchar(10),@StoreId) + ' ' + QUOTENAME(CONVERT(varchar,@StartDate,112)) + ',' 
+  QUOTENAME(CONVERT(varchar,@EndDate,112)) +')';