我一直在研究如何将变量传递给openquery。这是我建立的查询。
DECLARE @firstday int;
DECLARE @lastday int;
SELECT @firstday = CONVERT(nvarchar(8), (DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)), 112)
SELECT @lastday = CONVERT(nvarchar(8), (DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)), 112)
DECLARE @SqlCommand NVARCHAR(MAX) = N'SELECT * FROM OPENQUERY(EPAK,
''SELECT WOADAT,WOROUT,BCDESC,WDWO#,BCSIZE,BCCHG
FROM CUST INNER JOIN (BCDE INNER JOIN (WO2 INNER JOIN WO1
ON (WDCMP = WOCMP) AND (WDCUS# = WOCUS#) AND (WDWO# = WOWO#)) ON (BCCMPY = WDCMP)
AND (BCSIZE = WDSIZE) AND (BCCHG = WDCHG)) ON (CCMPNY = BCCMPY) AND (CCUST# = WDCUS#)
WHERE (((WOADAT) between @firstday and @lastday) AND ((WDCMP)=''08''))order by WDWO#'')'
EXEC sp_ExecuteSQL @SqlCommand;
我的链接服务器是DB2服务器,当我运行查询时出现以下错误
Incorrect syntax near '08'.
当我对它加倍时,它突出显示了这个
SELECT @lastday = CONVERT(nvarchar(8), (DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)), 112)
有人可以看看,让我知道错误是什么?
答案 0 :(得分:2)
我认为你还需要两个单引号:
((WDCMP)=''''08''''))
您有一个带引号的字符串作为查询传入。两个级别的引用。我认为问题发生在第一轮替代之后,产生了:
((WDCMP)='08'))
这“看起来”正确,但不适用于引用的子字符串。第一个引用结束子字符串,产生错误。