本文主要是介绍sql 使用where筛选时,字段空时,不做筛选,非空时筛选,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
需求说明:
1.查询“Name=赵” 且“Tel=180xxxxxxxx” 且“Address=西安预立数据科技有限责任公司“ 且“Email=155154xxx@qq.com”
2.当Name或Tel或Address或Email为空时不做筛选
方法一:
这种方法可以达到目的,但是sql语句不易扩展和维护,不推荐使用
SELECT TOP 1000 [Id],[Name],[Tel],[Address],[Email]FROM [hlltest].[dbo].[User]WHERE (name = @name AND Tel IS NULL AND Address IS NULL AND Email IS NULL)OR (name IS NULL AND Tel = @Tel AND Address IS NULL AND Email IS NULL)OR (name IS NULL AND Tel IS NULL AND Address = @Address AND Email IS NULL)OR (name IS NULL AND Tel IS NULL AND Address IS NULL AND Email = @Email)OR (name = @name AND Tel = @Tel AND Address IS NULL AND Email IS NULL)OR (name = @name AND Tel IS NULL AND Address = @Address AND Email IS NULL)---还有很多种组合条件.....
方法二:
--推荐使用isnull
DECLARE @name NVARCHAR(50) = '赵',@Tel NVARCHAR(50) = '180xxxxxxxx',@Address NVARCHAR(50) = '西安预立数据科技有限责任公司',@Email NVARCHAR(50) = '155154xxx@qq.com'SELECT TOP 1000 [Id],[Name],[Tel],[Address],[Email]FROM [hlltest].[dbo].[User]WHERE ISNULL(name,@name) = @nameAND ISNULL(Tel,@Tel) = @TelAND ISNULL(Address,@Address) = @AddressAND ISNULL(Email,@Email) = @Email
当Name,Tel,Address,Email存放是字符串空时,Isnull就不能使用, 可以使用case when 或 LEN 判断
方法一:
--使用case when
DECLARE @name NVARCHAR(50) = '赵',@Tel NVARCHAR(50) = '180xxxxxxxx',@Address NVARCHAR(50) = '西安预立数据科技有限责任公司',@Email NVARCHAR(50) = '155154xxx@qq.com'SELECT TOP 1000 [Id],[Name],[Tel],[Address],[Email]FROM [hlltest].[dbo].[User]WHERE (1 = (CASE WHEN Name = '' THEN 1 ELSE 0 END) OR Name = @name )AND (1 = (CASE WHEN Tel = '' THEN 1 ELSE 0 END) OR Tel = @Tel )AND (1 = (CASE WHEN Address = '' THEN 1 ELSE 0 END) OR Address = @Address )AND (1 = (CASE WHEN Email = '' THEN 1 ELSE 0 END) OR Email = @Email )
方法二:
--使用LEN
DECLARE @name NVARCHAR(50) = '赵',@Tel NVARCHAR(50) = '180xxxxxxxx',@Address NVARCHAR(50) = '西安预立数据科技有限责任公司',@Email NVARCHAR(50) = '155154xxx@qq.com'SELECT TOP 1000 [Id],[Name],[Tel],[Address],[Email]FROM [hlltest].[dbo].[User]WHERE (LEN(Name) = 0 OR Name = @name )AND (LEN(Tel) = 0 OR Tel = @Tel )AND (LEN(Address) = 0 OR Address = @Address )AND (LEN(Email) = 0 OR Email = @Email )
欢迎加群,日用儿童母婴分享大牌淘宝京东优惠券
这篇关于sql 使用where筛选时,字段空时,不做筛选,非空时筛选的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!