4

我正在尝试将变量传递给 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 provider "MSDASQL" for linked server "(null)" returned message "[Pervasive][ODBC Client Interface][LNA][Pervasive][ODBC Engine Interface]Error in predicate: TranDate = '(SELECT @ dDateTIME)' "

4

2 回答 2

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 
于 2013-05-17T19:55:28.517 回答
1

您的变量没有连接到字符串(它'''用 a 关闭字符串')来纠正这个问题(并执行必要的类型转换):

DECLARE @SQL NVARCHAR(1024) = 
 'SELECT 
        ID,
        TranDate,
        ProductID,
        CostValue,
        SalesValue,
        QtySold,
    FROM tblSales WHERE TranDate=''' + CAST(@dDateTIME AS VARCHAR(64)) + ''''

此外,您不能使用表达式或变量,OPENROWSET因此您需要通过EXEC()/调用它sp_executeSQL,请参阅;在 OPENROWSET 查询中使用变量

于 2013-05-17T11:20:23.173 回答