sql - 减少 SQL 中 if else 条件代码的更好方法

标签 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;

提前致谢。

问候, 安尼什

最佳答案

您可以使用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

关于sql - 减少 SQL 中 if else 条件代码的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44017448/

相关文章:

mysql - 如何在Mysql中选择NOT IN,但考虑到区分大小写?

php - 查询没有给出我想要的结果

sql-server - 如何重置 SQL Server 2008 用户名和密码

sql-server - 在 SQL Server 2012 中将 varbinary() 转换为 varchar(max) 时如何编码特定语言的字符?

按日期范围搜索的 SQL 查询

sql - 更新 SQL View ,对外部表值实现约束

sql - 在字符串中查找子字符串

sql - 在 SQL Server 中执行日期/时间减法

sql - 使用 SQL Server Express 进行 SQL Server Standard 开发?

sql - 根据日期删除一对值中的一个