如何在 OPENQUERY 中使用 Declare 变量

How can I use a Declare variable inside OPENQUERY

我在 SQL Server 2019

中有以下 SQL 查询
DECLARE @CoustomerCode nvarchar(255)

set @CoustomerCode = 1165

select * from tblCustomer CC 
outer apply(SELECT * FROM OPENQUERY ([132.20.28.36], 'SELECT * FROM RepServiceDB.dbo.Info('+ @CoustomerCode +')' ) as SR ) HH
where CC.fldCustomerCode = @CustomerCode

SQL 错误:

Incorrect syntax near '+'.

如果必须使用 OPENQUERY,则必须使用动态 SQL,因为调用 中的查询必须 是文字:

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

DECLARE @CoustomerCode nvarchar(255);
SET @CoustomerCode = N'1165'; --This is an nvarchar, so you should define it as one.

SET @SQL = N'SELECT *' + @CRLF +
           N'FROM dbo.tblCustomer CC ' + @CRLF +
           N'     OUTER APPLY(SELECT * FROM OPENQUERY ([132.20.28.36], ''SELECT * FROM RepServiceDB.dbo.Info('''''+ REPLACE(@CoustomerCode,'''','''''''''') +''''')'' ) as SR ) HH' + @CRLF +
           N'WHERE CC.fldCustomerCode = @CoustomerCode;';

EXEC sys.sp_executesql @SQL, N'@CoustomerCode nvarchar(255)',@CoustomerCode;

而且,是的,我确实在语句中用四个单引号 (') 替换了单引号。这是因为它是文字串,在文字串里面,在文字串里面,所以需要双重转义。