一种更好的方法来最小化SQL中if else条件的代码

时间:2017-05-17 06:44:46

标签: sql sql-server

我是SQL的新手。请检查以下代码。我试图通过使用@isActive bool属性从我的表中获取一些数据。如果这个bool是真的那么我只是添加一个额外的条件来获取值。我有点想出下面的代码,有没有其他可能的方法来最小化这段代码?

declare @firstname nvarchar(100);
declare @surname nvarchar(100) ;
declare @isActive bit ;

create table #Table1
(
    Serial_number int,
    Unique_Id uniqueidentifier
)
insert into #Table1
if @isActive='false'
Begin
select
    t.Guid
from UserTable t -- this table contains my data
where 
t.FirstName = @firstname
t.SurName = @surname
End
else
Begin
select
    t.Guid
from UserTable t
where 
t.FirstName = @firstname
t.SurName = @surname
t.isActive = @isActive -- this is the only codition I am adding extra for this if else codtion. 
End                    -- Is there a better way to minimize this code?

select * from #Table1
drop table #Table1;

提前致谢。

此致 阿尼什

1 个答案:

答案 0 :(得分:2)

您可以改为使用CASE,如下所示

insert into #Table1
select
    t.Guid
from UserTable t -- this table contains my data
where t.FirstName = @firstname
AND t.SurName = @surname
AND (@isActive = 'f' OR t.isActive = @isActive)

--Case Alternative
--AND ISNULL(t.isActive, 'a') = case when @isActive = 'f' then
--ISNULL(t.isActive, 'a') else @isActive end

注意:将@isActive的数据类型更改为CHARVARCHAR