我对 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;
提前致谢。
问候, 安尼什
最佳答案
您可以使用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
关于sql - 减少 SQL 中 if else 条件代码的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44017448/