设置要在多个SQL选择查询中使用的条件

时间:2012-12-21 19:16:31

标签: sql sql-server where-clause select-query

需要设置运行多个查询的条件,但只想更改一次。例如,要设置年份,期间,文档......

select * from tbl1 where tbl1.yr = year and ...
select * from tbl2 where tbl2.yr = year, and ...

3 个答案:

答案 0 :(得分:2)

创建视图:

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

答案 1 :(得分:1)

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)

答案 2 :(得分:1)

如果它们是真正不同的查询,而不是相关的,则可能需要使用动态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)