关于sql多条件查询[转]

/*以后我们做多条件查询,一种是排列结合,另一种是动态拼接SQL
如:我们要有两个条件,一个日期@addDate,一个是@name
第一种写法是 
*/
if (@addDate is not nulland (@name <> '')
select * from table where addDate = @addDate and name = @name
else if (@addDate is not nulland (@name ='')
select * from table where addDate = @addDate
else if(@addDate is   nulland (@name <> '')
select * from table where and name = @name
else if(@addDate is   nulland (@name = '')
select * from table
/*第二种就是动态组成SQL,通过exec来执行,我就不写,
昨天我想到一种办法 
*/
select * from table where (addDate = @addDate or @addDate is nulland (name = @name or @name = '')

declare @sql char(1000)
set @sql = 'select * from tablename where 1=1'
if condition1
set @sql=@sql+ 'and column1=?'
if condition2
set @sql=@sql+ 'and column2=?'
..
Exec(@sql)

--正确的书写格式应该是这样的:

ALTER PROCEDURE [dbo].[ap_intranetDHCPGetByIPAddressNameMacSel]
(
@IPAddress nvarchar (255) ,
@Name nvarchar (255) ,
@Mac nvarchar (255)
)
AS
SELECT
dhcpID,
[IPAddress],
[Name],
[Description],
[Mac],
[Switch],
[Port],
[AdminSvc],
[InternalSvc],
[ExternalSvc]
FROM
intranetdhcp
WHERE
(
(
[IPAddress] like '%'+ @IPAddress + '%'or
(
@IPAddress='')
and
(
[Name]like '%'+@Name+'%' or @Name=''and
(
[Mac] like '%'+@Mac+'%' or @Mac='')
order by
[IPAddress]

--对了 用了null之后,你的where条件可以改写为这样:
WHERE
IsNull(@IPAddress, IPAddress) = IPAddress And
IsNull(@Name, Name) = Name and
IsNull(@Mac, Mac) = Mac

/*
用''的确是方便,
但''与null的意义是不同的:
null表示没有输入,''表示输入了值为''
所以用null更容易理解,并且除字符型字段外其它为空的字段必须转换

null应该在调用时用DBNull.Value传给参数,而不是在sp中加:
if @IPAddress = '' set @IPAddress = null

另外Isnull()还是有漏洞的,也无法达到模糊查询。
但IPAddress,Name, Mac之类感觉上并不需要用到模糊查询
*/
原文地址:https://www.cnblogs.com/yiki/p/962298.html