在Select语句的哪个部分使用变量值

时间:2011-08-16 14:47:13

标签: sql sql-server select where-clause

以下是代码:

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子句中使用这个变量吗?

2 个答案:

答案 0 :(得分:2)

不,您不能使用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

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

答案 1 :(得分:1)

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