【问题标题】:Set criteria to be used in multiple SQL select queries设置要在多个 SQL 选择查询中使用的条件
【发布时间】:2012-12-09 08:58:13
【问题描述】:
需要设置运行多个查询的条件,但只想更改一次。比如想设置年、期、文档这样...
select * from tbl1 where tbl1.yr = year and ...
select * from tbl2 where tbl2.yr = year, and ...
【问题讨论】:
标签:
sql
sql-server
where-clause
select-query
【解决方案1】:
创建视图:
CREATE VIEW yourview AS
SELECT * from tbl1
UNION ALL
SELECT * from tbl2
然后查询它:
SELECT * FROM yourview
WHERE tbl1.yr = year AND ...
您可能还想知道每一行来自哪个表。这可以通过在视图中添加一个额外的列来实现:
CREATE VIEW yourview AS
SELECT 'tbl1' AS src, * from tbl1
UNION ALL
SELECT 'tbl2' AS src, * from tbl2
【解决方案2】:
如果它们是真正不同的查询,不相关,您可能不得不求助于动态 SQL,例如
DECLARE @sCondition VARCHAR(50)
SET @sCondition = 'yr = 2012'
DECLARE @sQuery1 VARCHAR(1000)
SET @sQuery1 = 'select * from tbl1 where ' + @sCondition
-- DECLARE other queries in similar faction OR combine multiple queries into single variable
EXEC (@sQuery1)
【解决方案3】:
CTE;注意:你应该有 same number of columns and matching datatypes from both tables 因为你正在做一个盲人union of select *
;with cte (myYear)
as (
select @year as myYear
)
select * from table1 t1 where t1.year in (select myYear from cte)
union all
select * from table2 t2 where t2.year in (select myYear from cte)