主select 语句大致如下,把它称作major:SELECT ...
UNION ALL
SELECT ...
UNION ALL
SELECT ...现在要做如下改动,当major结果集不为空时,就返回该结果集,否则
再执行另一条select语句: select B ,请问应该怎么写?多谢。

解决方案 »

  1.   

    create proc prc
    as
    begin
    set nocount on
    declare @count int
    select @count=count(*) from major
    if @count<>0
      select * from major
    else
      select * from B
    end
    --或者
    create proc prc
    as
    begin
    set nocount on
    select * from major
    if @@rowcount<>0
      select * from major
    else
      select * from B
    endexec prc
      

  2.   

    if exists(SELECT ...
    UNION ALL
    SELECT ...
    UNION ALL
    SELECT ...)
    begin 
      SELECT ...
      UNION ALL
      SELECT ...
      UNION ALL
      SELECT ...
    end
    else
    begin
      select B
    end
      

  3.   

    if exists(SELECT ...
    UNION ALL
    SELECT ...
    UNION ALL
    SELECT ...)
    begin 
      SELECT ...
      UNION ALL
      SELECT ...
      UNION ALL
      SELECT ...
    end
    else
    begin
      select B
    end
      

  4.   

    gahade, 你的这个写法是我能想到的,不知道这么写,major 查询语句是不是会执行两遍?
    一次在if exists执行,一次在不为空时?有效率问题吗?
      

  5.   

    或者改为这样,应该能快一些.if exists(SELECT ...1) or exists(SELECT ...2) or exists(SELECT ...3)
    begin 
      SELECT ...
      UNION ALL
      SELECT ...
      UNION ALL
      SELECT ...
    end
    else
    begin
      select B
    end
      

  6.   

    我是菜鸟,但是根据编程语言的一般特征,我猜应该可以把if exist里面的结果直接存到
    临时表里面吧,是不是可以呢?
      

  7.   

    还有一个问题,如果像上面所说的这样写的话,有没有可能把major语句:
    SELECT ...
    UNION ALL
    SELECT ...
    UNION ALL
    SELECT ..先存到一个字符串变量里,这样的话,每次对major的修改就不用担心要同时改两个地方了?
      

  8.   

    终于找到一个解决方法了,用临时表insert into #aaa
    SELECT ...
    UNION ALL
    SELECT ...
    UNION ALL
    SELECT ..if not existes (select * from #aaa)
        select B
    else
        select * from #aaa