选择条件匹配的数据,如果不匹配,则选择全部?

时间:2019-05-30 06:47:09

标签: sql sql-server

select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id

场景1:      @id ='user1'

dept1

场景2:     @id ='user5'

dept1
dept2
dept3
dept4

这是一个毫无意义的查询的样子

declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0

6 个答案:

答案 0 :(得分:2)

DECLARE @id VARCHAR(5) = 'user1';
--DECLARE @id VARCHAR(5) = 'user5';
  WITH  UsersAndDepartments
AS ( SELECT   *
    FROM     ( VALUES ( 'dept1', 'user1'), ( 'dept2', 'user2'),
            ( 'dept3', 'user3'), ( 'dept4', 'user4') ) x ( [department], [user] )
    )
SELECT  *
FROM    UsersAndDepartments ud1
WHERE   ud1.[user] = 
    CASE 
        WHEN EXISTS ( SELECT 1 FROM UsersAndDepartments ud2 WHERE ud2.[user] = @id ) THEN @id
        ELSE ud1.[user] 
    END

上面只是检查用户列是否存在ID的任何行,否则全部匹配。

答案 1 :(得分:1)

我会用一个简单的OR而不是CASE中的WHERE表达式来做到这一点。

通常,出于以下几个原因,您希望避免在CASE子句中使用WHERE表达式:

  • 几乎可以使用基本的布尔运算来简洁地编写逻辑。
  • (除了ANDORNOT之外,添加其他构造只会使人们更难以遵循逻辑。
  • 这几乎杀死了所有优化路径。

我建议:

with table1 as 
      select v.*
      from (values ('dept1', 'user1'),
                   ('dept2', 'user2'),
                   ('dept3', 'user3'),
                   ('dept4', 'user4')
           ) v([department], [user])
     )
select t1.*
from table1 t1
where t1.[user] = @id or
      not exists (select 1 from table1 t1 where t1.user = @id);

答案 2 :(得分:0)

您可能必须先进行类似这样的检查

Declare @RowCount int
Select @RowCount = (select count(*) from [Table] Where [Column] = 'xxx')

If @RowCount > 0
 begin 
  Select 1 -- put code here if records
 end
else
 begin
  Select 2 -- put code here if no records
 end

答案 3 :(得分:0)

declare @tab table (id int , value varchar(10))
declare @id int = 4

insert into @tab
select 1,'Ajay'
union all
select 2,'Ajay1'
union all
select 3,'Ajay2'
union all
select 4,'Ajay3'
union all
select 5,'Ajay4'

select * from @tab 
where id = case when exists (select * from @tab where id = @id) then @id else id end

答案 4 :(得分:0)

您可以尝试以下操作:

DECLARE @id varchar(12) = 'user1'

IF EXISTS(SELECT COUNT(*) FROM table1 WHERE [user] = @id)
BEGIN
SELECT * FROM table1 WHERE [user] = @id
END
ELSE
BEGIN
SELECT * FROM table1
END

您还可以在以下位置阅读有关“ EXISTS”语法的更多信息: https://docs.microsoft.com/en-us/sql/t-sql/language-elements/exists-transact-sql?view=sql-server-2017

答案 5 :(得分:0)

如果将“如果存在”逻辑与实际查询分开,则可以有一个更好的执行计划:

DECLARE @id varchar(10) = 'user5'
DECLARE @table TABLE ([department] varchar(10), [user] varchar(10))

insert into @table values 
                    ('dept1','user1'),
                    ('dept2','user2'),
                    ('dept3','user3'),
                    ('dept4','user4')

DECLARE @exists BIT = 
(SELECT 1 FROM @table WHERE [user] = @id)

SELECT department FROM @table
WHERE [user] = CASE @exists WHEN 1 THEN @id ELSE [user] END