我试图将一个变量传递给 OPENROWSET 中的 SELECT 语句,但我一直收到错误
DECLARE @dDateTIME DATE
SET @dDateTIME = (SELECT SalesDate FROM dbo.SalesDate)
INSERT INTO dbo.tblSales
SELECT * FROM OPENROWSET('MSDASQL', 'dsn=mydsn;uid=myid;pwd=mypwd;',
'SELECT
ID,
TranDate,
ProductID,
CostValue,
SalesValue,
QtySold,
FROM tblSales WHERE TranDate='' + @dDateTIME + ''')
DECLARE @dDateTIME DATE
SET @dDateTIME = (SELECT SalesDate FROM dbo.SalesDate)
DECLARE @SQL NVARCHAR(1024) =
'SELECT
ID,
TranDate,
ProductID,
CostValue,
SalesValue,
QtySold,
FROM tblSales WHERE TranDate=''' + CAST(@dDateTIME AS VARCHAR(64)) + ''''
DECLARE @RunSQL NVARCHAR(max)
SET @RunSQL=
'SELECT * FROM OPENROWSET (''MSDASQL'', ''dsn=mydsn;uid=myid;pwd=mypwd;'',''EXEC @SQL'')'`
我使用什么语法来应用
@SQL
?我得到的错误是:
最佳答案
您的变量没有连接到字符串(它的 '''
用 '
关闭字符串)来纠正这个(并执行必要的类型转换):
DECLARE @SQL NVARCHAR(1024) =
'SELECT
ID,
TranDate,
ProductID,
CostValue,
SalesValue,
QtySold,
FROM tblSales WHERE TranDate=''' + CAST(@dDateTIME AS VARCHAR(64)) + ''''
此外,您不能将表达式或变量与
OPENROWSET
一起使用,因此您将需要通过 EXEC()
/sp_executeSQL
调用它,请参阅; Using a Variable in OPENROWSET Query关于SQL SELECT * FROM OPENROWSET 带变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16607433/