一句话完成多条件查询

例如有这么一张表:



有时我们需要根据名字进行查询;
有时我们需要根据年龄进行查询;
有时又需要根据名字和年龄进行查询;

以前都是通过拼接sql语句完成:

declare @sql nvarchar(500)

set @sql = 'select * from table1 where 1=1'

if(not @name is null)
    set @sql = @sql + ' and name=''' + @name + ''''
if(not @age is null)
    set @sql = @sql + ' and age>' + convert(varchar,@age)

今天发现不用拼接sql语句,一句话就能完成sql多条件查询:

MSSQL版:
select * from table1 where ([name]=@name or @name is null) and ([age]>@age or @age is null)


ACCESS版:
select * from table1 where (name=[@name] or isnull([@name])) and (age>[@age] or isnull([@age]))


评论: 0 | 引用: 0 | 查看次数: 4169
发表评论
登录后再发表评论!