【问题标题】:using variable values in where part of Select statement在 Select 语句的 where 部分中使用变量值
【发布时间】:2011-08-16 14:47:12
【问题描述】:

代码如下:

declare
    @allcounterids varchar(max),
    @counteridquery varchar(max);

select
    @allcounterids = stuff((
    select 
            '],[' + cast([CounterId] as varchar(32))
        from
            AllCounters
        WHERE DateTime > '2011-08-15' and DateTime < '2011-08-19' and [Type] = 1
        for xml path('')), 1, 2, '') + ']';

选择语句

SELECT [Type], [DateTime], Value, AllCounters.CounterId
            FROM AllCounters
            WHERE CounterId IN @allcounterids

如您所见,我已经创建了变量“@allcounterids”并在其中填充了数据,我的问题是我可以在 Select 的 where 子句中使用这个变量吗?

【问题讨论】:

    标签: sql sql-server select where-clause


    【解决方案1】:

    不,您不能将 CSV 字符串与 IN 过滤器(“谓词”)一起使用。如果没有动态 SQL,SQL 就无法以这种方式工作:在这种情况下不需要这样做

    可以一次性完成,所以

    SELECT [Type], [DateTime], Value, AllCounters.CounterId
    FROM AllCounters
    WHERE CounterId IN
        (select [CounterId]
        from AllCounters
        WHERE DateTime > '2011-08-15' and DateTime < '2011-08-19' and [Type] = 1
        )
    

    但是,既然如此,为什么不直接这样做呢?

    SELECT [Type], [DateTime], Value, AllCounters.CounterId
    FROM AllCounters
    WHERE DateTime > '2011-08-15' and DateTime < '2011-08-19' and [Type] = 1
    

    除非您的问题不完整且缺少信息...

    【讨论】:

    • 我正在做这个stackoverflow.com/questions/7076628/…的bcz,现在bcz的性能我正在删除所有额外的东西,你可以在帖子中看到我创建了一个只有不同ID的视图然后做innerjoin 与它...所以想要自定义此查询并提高其性能
    • @dvlpr: 1. 这里的问题不正确 2. 你接受了最后一个问题的答案:为什么? 3. 这个问题有什么意义。而且“bcz”不是英语
    • 我接受它是因为 [sorry for bcz] 在那个问题中我询问了关于提高我发布的查询的性能,我接受它的答案提高了性能,并且我已经指出了查询的哪一部分花费的时间更少,现在我正在尝试自己自定义(通过将查询分解为多个部分来更多的第二部分)......所以当我遇到在 where 子句中使用变量时,我问了这个问题......只是想让它变得更好,如果你可以在这里或我的最后一个问题中帮助我
    【解决方案2】:

    我以前用过这个(免责声明:我用的是 MS SQL Server,你没有指定 RDBMS),但它只适用于动态 SQL。构造一个查询字符串,清理所有输入,然后执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 2014-12-04
      • 1970-01-01
      相关资源
      最近更新 更多