欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

存储过程为参数NULL时的处理方法

程序员文章站 2022-03-29 14:25:07
准备一些数据: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Goods]( [Projname] [nvarchar](10) NULL, [version] [nvarchar](10) NULL, [s ......

准备一些数据:

 

set ansi_nulls on
go

set quoted_identifier on
go

create table [dbo].[goods](
    [projname] [nvarchar](10) null,
    [version] [nvarchar](10) null,
    [state] [nvarchar](3) null
) on [primary]
go


insert into  [dbo].[goods] ([projname],[version],[state])
values
(n'a项目',n'启动会版',n'已审核'),
(n'a项目',n'方案版',n'已审核'),
(n'a项目',n'施工图版',n'未审核'),
(n'b项目',n'    启动会版',n'未审核'),
(n'b项目',n'    方案版',n'未审核'),
(n'b项目',n'    施工图版',n'未审核')

go

 

先来看看下面2句sql语句,参数有值和null所查询到的结果:

 

declare @projname nvarchar(10) = n'a项目'
select [projname],[version],[state] from [dbo].[goods] where [projname] = @projname
go


declare @projname nvarchar(10) = null
select [projname],[version],[state] from [dbo].[goods] where [projname] = @projname
go

 

方法一:

 

declare @projname nvarchar(10) = n'a项目'
select [projname],[version],[state] from [dbo].[goods] where [projname] = @projname
go


declare @projname nvarchar(10) = null
select [projname],[version],[state] from [dbo].[goods] where [projname] =
case when @projname is null then [projname] else @projname end

go

 

方法二:

 

declare @projname nvarchar(10) = n'a项目'
select [projname],[version],[state] from [dbo].[goods] where [projname] = @projname
go


declare @projname nvarchar(10) = null
select [projname],[version],[state] from [dbo].[goods] where [projname] = @projname
 or @projname is null
go

 

方法三:

 

declare @projname nvarchar(10) = n'a项目'
select [projname],[version],[state] from [dbo].[goods] where [projname] = @projname
go


declare @projname nvarchar(10) = null
select [projname],[version],[state] from [dbo].[goods] where [projname] = 
iif(isnull(@projname, n'') = n'', [projname], @projname)
go

 

方法四:

 

declare @projname nvarchar(10) = n'a项目'
select [projname],[version],[state] from [dbo].[goods] where [projname] = @projname
go


declare @projname nvarchar(10) = null
select [projname],[version],[state] from [dbo].[goods] where [projname] = 
@projname or isnull(@projname, n'') = n''
go

 

方法五:

 

 

declare @projname nvarchar(10) = n'a项目'
select [projname],[version],[state] from [dbo].[goods] where [projname] = @projname
go


declare @projname nvarchar(10) = null
select [projname],[version],[state] from [dbo].[goods] where [projname] =
 iif(@projname is null, [projname], @projname)
go

 

方法六:

 

declare @projname nvarchar(10) = n'a项目'
select [projname],[version],[state] from [dbo].[goods] where [projname] = @projname
go

declare @projname nvarchar(10) = null

if len(isnull(@projname,'')) > 0
    select [projname],[version],[state] from [dbo].[goods]  where [projname] = @projname
else
    select [projname],[version],[state] from [dbo].[goods]
go