需要设置运行多个查询的条件,但只想更改一次。例如,要设置年份、期间、文档,以便...
select * from tbl1 where tbl1.yr = year and ...
select * from tbl2 where tbl2.yr = year, and ...
需要设置运行多个查询的条件,但只想更改一次。例如,要设置年份、期间、文档,以便...
select * from tbl1 where tbl1.yr = year and ...
select * from tbl2 where tbl2.yr = year, and ...
创建视图:
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
与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)
如果它们是真正不同的查询,不相关,您可能不得不求助于动态 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)