複数のクエリを実行するための条件を設定する必要があるが、変更は 1 回だけにしたい。たとえば、年、期間、ドキュメントを設定して...
select * from tbl1 where tbl1.yr = year and ...
select * from tbl2 where tbl2.yr = year, and ...
複数のクエリを実行するための条件を設定する必要があるが、変更は 1 回だけにしたい。たとえば、年、期間、ドキュメントを設定して...
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)