【问题标题】: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 ...

【问题讨论】:

  • 你为什么要这样做?
  • 澄清一下:什么是 RDBMS

标签: 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)
      

      【讨论】:

        猜你喜欢
        • 2021-11-11
        • 2011-12-07
        • 1970-01-01
        • 2019-07-21
        • 2020-06-21
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 2021-08-16
        相关资源
        最近更新 更多