我试图将一个变量传递给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
?
我得到的错误是:
错误是:OLE DB提供程序“MSDASQL”链接服务器“(null)”返回消息“[Pervasive] [ODBC客户端接口] [LNA] [Pervasive] [ODBC引擎接口]谓词错误:TranDate =' (SELECT @dDateTIME)'“
答案 0 :(得分:1)
您的变量未连接到字符串(其'''
以关闭带有'
的字符串)以更正此字符(并执行必要的类型转换):
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
答案 1 :(得分:1)
您可以动态创建SQL语句,然后运行该命令。
DECLARE @dDateTIME DATE,
@RunSQL NVARCHAR(max)
SET @dDateTIME = (SELECT SalesDate FROM dbo.SalesDate)
SELECT @RunSQL =
'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=''''' + CONVERT(nvarchar, @dDateTIME, 112) + ''''''')'
--PRINT @RunSQL
EXEC sp_executesql @RunSQL