使用链接服务器将参数化动态查询从SQL Server传递到MySQL数据库时出现问题

时间:2013-07-08 17:50:56

标签: mysql sql-server dynamic linked-server parameterized-query

我正在尝试使用SQL Server数据库中的链接服务器查询MySQL数据库。我创建了一个参数化的动态SQL查询,当我运行它时,它没有错误,但它返回0行。

如果我对参数进行硬编码,则返回我请求的行的数据。

在参数化查询方面,有没有处理MySQL的技巧?

此语法返回0行:

DECLARE @SQL NVARCHAR(MAX), 
        @Params VARCHAR(MAX)

SET @SQL = N'SELECT * FROM OPENQUERY(MYSQL, ''SELECT LoanNumber  
             FROM plms.vw__bid_dd_overlay 
             WHERE LoanNumber IN (@MyParams);'')'

SET @Params = '1000001289,1000001294,1000001296,1000001303,1000001304,1000001306,1000001308'; 

EXEC sp_executesql @SQL, N'@MyParams VARCHAR(MAX)', @Params

这将返回7:

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = N'SELECT * FROM OPENQUERY(MYSQL, ''SELECT LoanNumber  
                                              FROM plms.vw__bid_dd_overlay 
                                              WHERE LoanNumber IN  (1000001289,1000001294,1000001296,1000001303,1000001304,1000001306,1000001308);'')'

EXEC sp_executesql @SQL; 

非常感谢任何协助。

1 个答案:

答案 0 :(得分:0)

您需要准备一个语句然后执行它:

SET @Params = '1000001289,1000001294,1000001296,1000001303,1000001304,1000001306,1000001308'; 

SET @SQL = CONCAT('SELECT LoanNumber  
         FROM plms.vw__bid_dd_overlay 
         WHERE LoanNumber IN (' , @MyParams , ' );';

PREPARE statement FROM @SQL;

EXECUTE statement;

Reference to the mySQL manual