概述
需求说明:
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) = @name
AND ISNULL(Tel,@Tel) = @Tel
AND ISNULL(Address,@Address) = @Address
AND 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筛选时,字段空时,不做筛选,非空时筛选的全部内容,希望文章能够帮你解决sql 使用where筛选时,字段空时,不做筛选,非空时筛选所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复