将参数传递给Openquery select语句

时间:2017-07-07 16:42:53

标签: sql sql-server tsql openquery

我有一个查询:

DECLARE @sql2 nvarchar(max), @counts int, @maxdate date;

SELECT @maxdate=isnull(Max(btestDateResultBack),'01/01/1900') FROM BloodTests
PRINT @maxdate
print @maxdate

SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs, 
            '+CAST(@maxdate AS varchar(20))+', count(*) AS Count 
             FROM blood_tests WHERE btestResult = 1 
             AND btestDateResultBack >''''' +convert(varchar(30), @maxdate, 121)  
             +''''''

SET @sql2 = 'SELECT * From openquery(MYSQL_donors, '''+@sql2+''')'

EXEC sp_executesql @sql2

正确返回DonorIDs和Count列,但是带有变量' + CAST(@maxdate AS varchar(20))+'的列将日期作为别名返回到列(请参见下图)。

Figure 1 - query result set 在WHERE子句中使用@maxdate可以正常工作。

如何在SELECT语句的主体中使用@maxdate?

我已经看到了很多关于如何在WHERE子句中使用此变量的答案,但我还没有看到有人讨论将其添加到SELECT语句选择列表中。

最终工作解决方案

DECLARE @sql nvarchar(max)         ,@ sql2 nvarchar(max)         ,@ sql3 nvarchar(max)         ,@counts int         ,@ blodtestdonors int         ,@ maxdate date;

- 查找并删除今天的血液测试 SELECT @maxdate = isnull(Max(btestDateResultBack),' 1900-01-01')FROM BloodTests;

PRINT @maxdate;

SET @ sql2 =' SELECT CONVERT(GROUP_CONCAT(btestDonor)使用utf8)AS DonorIDs,         '''' + CAST(@maxdate AS varchar(30))+''''&# 39; AS日期,         count(*)AS Count FROM blood_tests         在哪里btestResult = 1 AND         btestDateResultBack>'''' + convert(varchar(30),@ maxdate,121)+'''& #39;''

SET @ sql2 =' SELECT *来自openquery(MYSQL_donors,''' + @ sql2 +''')&#39 ;

EXEC sp_executesql @ sql2

感谢@bielawski和@Prdp的帮助和澄清。我很感激。感谢@ stan-shaw进行代码格式化。

2 个答案:

答案 0 :(得分:1)

使用<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_search" android:title="@string/search" android:icon="@drawable/ic_search_black_36dp" app:showAsAction ="ifRoom|collapseActionView" app:actionViewClass ="android.support.v7.widget.SearchView" /> </menu> 将参数值传递给您的查询

sp_executesql

我不明白的是,你如何重视SET @sql2 = 'SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs, @maxdate, count(*) AS Count FROM blood_tests WHERE btestResult = 1 AND btestDateResultBack > @maxdate' exec sp_executesql @sql2,N'@maxdate date',@maxdate = @maxdate

答案 1 :(得分:1)

我测试了这个。它有正确的引用,它的工作原理。问题是错误的引用和未命名的日期列的组合。

DECLARE @maxdate DATE = '2017-6-29';
DECLARE @sql2 NVARCHAR(max) = 
    'SELECT * From openquery(MYSQL_donors, ''SELECT CONVERT(GROUP_CONCAT(btestDonor) USING utf8) AS DonorIDs, 
    '''''+CAST(@maxdate AS varchar(20))+''''' AS DDate, count(*) AS Count 
       FROM blood_tests WHERE btestResult = 1 
        AND btestDateResultBack >''''' +convert(varchar(30), @maxdate, 121)+''''''')'

EXEC (@sql2);