我是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;
提前致谢。
此致 阿尼什
答案 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
的数据类型更改为CHAR
或VARCHAR