SQL SELECT * FROM OPENROWSET with Variable

我试图将一个变量传递给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?

我得到的错误是:

The error is :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)’ “

最佳答案 您的变量没有连接到字符串(其”’用关闭带有’的字符串)来纠正这个(并执行必要的类型转换):

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

点赞