木子屋 Dnawo's BLOG

一句话完成多条件查询

👤 dnawo 📅 2009-08-17 👁 4865 👍 0 💬 0 🔄 来源:本站原创
例如有这么一张表:

图片

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

以前都是通过拼接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)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 .NET数据集(xsd)使用模糊查询 下一篇 → .NET数据集(xsd)使用in查询