2

複数のクエリを実行するための条件を設定する必要があるが、変更は 1 回だけにしたい。たとえば、年、期間、ドキュメントを設定して...

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

3 に答える 3

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
于 2012-12-21T19:17:59.707 に答える
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)
于 2012-12-21T19:23:36.640 に答える
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)
于 2012-12-21T19:25:56.580 に答える