查询功能的SQL。

表A有100个字段(或者更多),全是数字类型.
我现在想查询只要满足有一个字段等于20的记录,该如何做?

当然可以:
select * from A where field1=20 or field2=20 or field3=20.........
可是这样很不爽,相信有简单的语句,望指点!

进一步,如果字段有的为字符串类型,有的为日期,有的为数字的,同样的查询要求,又该如何。




"表A有100个字段(或者更多),全是数字类型.我现在想查询只要满足有一个字段等于20的记录"

这个好办,都是等于嘛,可以用:

select * from A where 20 in(field1,field2,...field20)


--如果不想写列名,可以用动态语句:

declare @sql Nvarchar(4000)
set @sql=''
select @sql=@sql+N','+quotename(name) from syscolumns where id=object_id(N'A')
set @sql='select * from A where 20 in('+stuff(@sql,1,1,N'')+N')'
exec(@sql)


--如果考虑字段类型,那就麻烦一点,要过滤掉不符合要求的字段

declare @sql Nvarchar(4000)
set @sql=''
select @sql=@sql+N','+quotename(c.name)
from syscolumns c,systypes t
where c.id=object_id(N'A')
and c.xusertype=t.xusertype
and t.name not in('binary','bit','image','timestamp','uniqueidentifier')
and t.name not like '%binary'
and t.name not like '%text'
and t.name not like '%datetime'
set @sql='select * from A where 20 in('+stuff(@sql,1,1,N'')+N')'
exec(@sql)


--如果还要考虑字符型字段能否转换为数字,改用:

declare @sql Nvarchar(4000)
set @sql=''
select @sql=@sql+N','+case when t.name like '%char' then N'case isnumeric('+quotename(c.name)+')=1 then '+quotename(c.name)+' end)' else quotename(c.name) end
from syscolumns c,systypes t
where c.id=object_id(N'A')
and c.xusertype=t.xusertype
and t.name not in('binary','bit','image','timestamp','uniqueidentifier')
and t.name not like '%binary'
and t.name not like '%text'
and t.name not like '%datetime'
set @sql='select * from A where 20 in('+stuff(@sql,1,1,N'')+N')'
exec(@sql)

--当然,你也可以把数字比较改为字符比较
declare @sql Nvarchar(4000)
set @sql=''
select @sql=@sql+N','+quotename(name) from syscolumns where id=object_id(N'A')
set @sql='select * from A where N''20'' in('+stuff(@sql,1,1,N'')+N')'
exec(@sql)

posted on 2005-03-18 10:37  轻松逍遥子  阅读(304)  评论(0编辑  收藏  举报