怎样根据字段值取字段名?(在线...)

weijian0131 2003-10-16 01:31:59
我想根据字段的值取字段名,能实现吗?如何实现?
...全文
36 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2003-10-16
  • 打赏
  • 举报
回复
--例子:

--创建被查询的表
create table tb(a varchar(10),b varchar(10))
insert into tb values('aa','bb')

--查询
declare @aa varchar(10),@sql nvarchar(1000),@re bit
set @aa='bb' --要查询的字段的值

declare @fdname sysname
declare #tb cursor for select name from syscolumns where object_id('tb')=id
open #tb
fetch next from #tb into @fdname
while @@fetch_status=0
begin
set @sql='set @re=case when exists(select 1 from tb where '+@fdname+'='''+@aa+''') then 1 else 0 end'
exec sp_executesql @sql,N'@re bit output',@re output
if @re=1 goto lbexit
fetch next from #tb into @fdname
end
lbexit:
close #tb
deallocate #tb

select 所属字段=@fdname

--删除测试环境.
drop table tb
zjcxc 2003-10-16
  • 打赏
  • 举报
回复
可以用类似下面的方法:

declare @aa varchar(10),@sql nvarchar(1000),@re bit
set @aa='aa' --要查询的字段的值

declare @fdname sysname
declare #tb cursor for select name from syscolumns where object_id('表名')=id
open #tb
fetch next from #tb into @fdname
while @@fetch_status=0
begin
set @sql='set @re=case when exists(select 1 from 表名 where '+@fdname+'='''+@aa+''') then 1 else 0 end'
exec sp_executesql @sql,N'@re bit output',@re output
if @re=1 goto lbexit
fetch next from #tb into @fdname
end
lbexit:
close #tb
deallocate #tb

select 所属字段=@fdname
weijian0131 2003-10-16
  • 打赏
  • 举报
回复
aa可能是字段PJName1的值,也可能是PJName2、PJName3、PJName4的值,我要知道aa这个值是那个字段的。
注:aa只可能是其中的一个字段的值。
SilverSands 2003-10-16
  • 打赏
  • 举报
回复
我想不可以!
因为你要是想知道aa,那就的检索,要检索就的知道字段名。

也许没有理解好楼主的意思.
weijian0131 2003-10-16
  • 打赏
  • 举报
回复
比如说字段名为PJName1的值为aa,我想根据aa这个值取得字段名
welyngj 2003-10-16
  • 打赏
  • 举报
回复
不懂意思

22,206

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧