在 ANSI SQL 中设置变量

sla*_*law 5 sql ansi-sql netezza

我是 SQL 新手,一直在寻找一种在 ANSI SQL 中设置变量的方法。我有这个:

select * from table1
where first_date > '2014-01-01'
and where second_date = '2014-01-01'
and where third_date < '2014-01-01'
Run Code Online (Sandbox Code Playgroud)

但我希望有这样的事情:

set x = '2010-12-31'
select * from table1
where first_date > x
and where second_date = x
and where third_date < x
Run Code Online (Sandbox Code Playgroud)

我读过有关存储过程的内容,但对于看似简单的事情来说,这似乎有点矫枉过正。我正在 Netezza 上运行,但我想要一个也可以在其他数据库上运行的通用解决方案。

小智 7

标准 (ANSI) SQL 没有变量。但是,您可以在标准 SQL 中执行的操作是使用公用表表达式仅获取该值一次。

以下是 ANSI SQL:

with data (the_date) as (
    values (date '2014-01-01')
)
select *
from table1
where first_date > (select the_date from data)
  and second_date = (select the_date from data)
  and third_date < (select the_date from data);
Run Code Online (Sandbox Code Playgroud)

上述内容适用于大多数 DBMS。并非所有人都支持values这样的子句,但通常可以使用简单的select语句来解决这个问题。

由于我从未使用过 Netezza,所以我不知道它是否支持行构造函数(子句values)或公用表表达式(with子句)

此外,某些 SQL 客户端还能够定义在 SQL 实际发送到数据库服务器之前替换的变量。