我试图在传递查询中使用参数问题是当我设置语句时我得到
' +'附近的语法不正确。期待')'
我之前已经这样做了所以我不确定我现在做错了什么。我已经缩短了下面的查询,给出了要点。
DECLARE @WORK_DATE AS VARCHAR(20)
SET @WORK_DATE = '20160210'
SELECT * FROM OPENQUERY(DATA_BASE_1,
'SELECT EMPLOYEE.EMPLOYEE_NUMBER AS EMPLOYEE_ID
FROM TABLE_1 EMPLOYEE
LEFT JOIN TABLE_2 PERSON
ON EMPLOYEE.EMPLOYEE_NUMBER = PERSON.EMPLOYEE_NUMBER
AND PERSON.WORK_DATE = '''''+ @WORK_DATE + '''''')
答案 0 :(得分:1)
来自Transact-SQL OPENQUERY documentation:
<强>说明强>
OPENQUERY不接受其参数的变量。
执行此操作的一种方法是将变量传递给存储要执行的查询的字符串,然后执行它。
DECLARE @SQL_TO_EXEC NVARCHAR(MAX), @WORK_DATE VARCHAR(20)
SET @WORK_DATE = '20160210'
SET @SQL_TO_EXEC = 'SELECT * FROM OPENQUERY(DATA_BASE_1, ''SELECT EMPLOYEE.EMPLOYEE_NUMBER AS EMPLOYEE_ID FROM TABLE_1 EMPLOYEE LEFT JOIN TABLE_2 PERSON ON EMPLOYEE.EMPLOYEE_NUMBER = PERSON.EMPLOYEE_NUMBER AND PERSON.WORK_DATE = '''''+ @WORK_DATE + ''''''')'
EXEC (@SQL_TO_EXEC)