日期:2014-05-17 浏览次数:20495 次
create proc testName
@ContactName varchar(20),
@ContactTitle varchar(20),
@ContactAddress varchar(20)
as
begin
select * from Customers
where ...
end
判断传递进来的3个参数是否为空 如果不为空就添加到后面的where条件中
我知道用if判断,但是不知道语法如何写
where (@ContactName is null or @ContactName=ContactName) and (@ContactTitle is null or @ContactTitle=ContactTitle) and (@ContactAddress is null or @ContactAddress=ContactAddress)
create proc testName
@ContactName varchar(20),
@ContactTitle varchar(20),
@ContactAddress varchar(20)
as
begin
declare @sql nvarchar(max),@whereSql nvarchar(max)
set @whereSql=''
if @ContactName<>'' set @whereSql=@whereSql+' and ContactName='''+@ContactName+''''
if @ContactTitle<>'' set @whereSql=@whereSql+' and ContactTitle='''+@ContactTitle+''''
if @ContactAddress<>'' set @whereSql=@whereSql+' and ContactAddress='''+@ContactAddress+''''
set @sql= 'select * from Customers where 1=1'+@whereSql
exec(@sql)
end