SQL if statment

时间:2018-02-14 08:59:01

标签: sql

我有这个SQL查询:

Select 
   * from dbo.Users 
WHERE 
   numOfScans == 0 feedback >= {0} 
AND 
   feedback <= {1} 
ORDER BY 
   lastScan ASC

它为所有用户提供了numOfScans为零的信息。 我有另一个案例,如果SELECT给我带来零结果,那么我不想使用numOfScans,例如:

Select 
  * from dbo.Users 
WHERE 
  feedback >= {0} AND feedback <= {1} 
ORDER BY 
  lastScan ASC

可以在同一个查询中执行此操作吗?或者我需要一个新的查询?

4 个答案:

答案 0 :(得分:2)

你可以用联盟来表达这个:

SELECT *
FROM dbo.Users 
WHERE numOfScans == 0 AND feedback BETWEEN {0} AND {1}
UNION ALL
SELECT *
FROM dbo.Users 
WHERE
    feedback BETWEEN {0} AND {1} AND
    (SELECT COUNT(*) FROM dbo.Users
     WHERE numOfScans == 0 AND feedback BETWEEN {0} AND {1}) = 0
ORDER BY lastScan;

这里的基本思想是,如果联合的前半部分返回任何记录,那么后半部分将为空集,反之亦然。

答案 1 :(得分:0)

您可以将第一个查询的结果放在temp变量中,并检查是否

@temp==0 then
Select * from dbo.Users 
WHERE feedback >= {0} AND feedback <= {1} 
ORDER BY lastScan ASC

答案 2 :(得分:0)

选项:

使用存储过程

create procedure  procsample  @first varchar(10),@second varchar(10) as
begin
  declare @sql varchar(10);

    Select @sql= count(1) from dbo.Users 
     WHERE numOfScans == 0 feedback >= @first AND feedback <= @second;


   if(@sql=0)

   Select * from dbo.Users 
   WHERE feedback >= @first AND feedback <= @second
   ORDER BY lastScan ASC;

   else

   Select * from dbo.Users 
   WHERE numOfScans == 0 feedback >= @first AND feedback <= @second
   ORDER BY lastScan ASC;

end

答案 3 :(得分:0)

尝试使用exists语句。 仅当这些记录存在时才会应用过滤器

Select * from dbo.Users
WHERE feedback >= {0} AND feedback <= {1} AND
(numOfScans = 0 OR NOT Exists(
        Select * from dbo.Users 
        WHERE numOfScans == 0)
)
 ORDER BY lastScan ASC