高分求助!一个表里面只有一条记录,各个字段的内容都不同,我想根据内容得到字段名字,可以嘛?谢谢

Iris 2003-09-13 11:58:34
一个表里面只有一条记录,我想根据,各个字段的内容都不同,我想根据内容得到字段名字,可以嘛?谢谢
...全文
35 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
saucer 2003-09-14
  • 打赏
  • 举报
回复
the dumb way is to do

select columnname=case
when col1='yourcontent' then 'col1'
when col2='yourcontent' then 'col2'
...
else '' end from yourtable

but try

use pubs
go

declare @content varchar(100)
declare @sql varchar(8000), @table varchar(30)
set @content = 'White'
select @table = 'authors', @sql = 'select top 1 columnname=case '

select @sql = @sql + ' when ' + name + ' = ''' + @content + ''' then ''' + name + ''' '
from syscolumns where object_name(id) = @table
and (xtype=167 or xtype=175 or xtype=239 or xtype=231) --only on char/nchar/vchar/nvarchar

set @sql = @sql + ' else '''' end from ' + @table

exec(@sql)

zjcxc 元老 2003-09-14
  • 打赏
  • 举报
回复
用这个存储过程就可以啦,将'表'替换成你的表名:

--得到i的值
create proc p_getfd
@值 int, --要查询的字段的值
@i int output --查询到的i的值
as
declare @fdname varchar(250) --字段名
declare @chk bit --检测是否存在
declare @sql nvarchar(4000) --检测语句
declare #tb cursor for select name form syscolumns where object_id('表')=id
open #tb
fetch next from #tb into @fdname
while @@fetch_status=0
begin
set @sql='select @chk=case ['@fdname+'] when '+cast(@fdvalue as varchar)+' then 1 else 0 end from 表'
exec sp_executesql @sql,N'@chk bit output',@chk output
if @chk=1
begin
set @i=cast(right(@fdname,len(@fdname)-4) as int)
break
end
fetch next from #tb into @fdname
end
deallocate #tb
go


--调用:
declare @i int
exec p_getfd 20030101,@i output
print @i`
Iris 2003-09-14
  • 打赏
  • 举报
回复
谢谢大家的帮助

我的需求是:
表里面有一些字段:DATE1,DATE2,DATE3,......,DATEi
i不固定,随着系统的设置而变
这些列对应的值可能是20030101,20030102,20030103,......
就是按照日历顺次排下去,我现在想得到i的值

thanks
zjcxc 元老 2003-09-14
  • 打赏
  • 举报
回复
上面只是针对字符型字段,为了通用,可以修改检测语句:
set @sql='select @chk=case ['@fdname+'] when '''+@fdvalue+''' then 1 else 0 end from 表'

为:
set @sql='select @chk=case cast(['@fdname+'] as varchar) when '''+@fdvalue+''' then 1 else 0 end from 表'


zjcxc 元老 2003-09-14
  • 打赏
  • 举报
回复
可以用下面的方法:

declare @fdname varchar(250) --字段名
declare @fdvalue varchar(500) --字段值
declare @chk bit --检测是否存在
declare @sql nvarchar(4000) --检测语句
set @fdvalue='要查询字段的值'
declare #tb cursor for select name form syscolumns where object_id('表名')=id
open #tb
fetch next from #tb into @fdname
while @@fetch_status=0
begin
set @sql='select @chk=case ['@fdname+'] when '''+@fdvalue+''' then 1 else 0 end from 表'
exec sp_executesql @sql,N'@chk bit output',@chk output
if @chk=1
begin
print @fdname
break
end
fetch next from #tb into @fdname
end
deallocate #tb

yujohny 2003-09-14
  • 打赏
  • 举报
回复
能不能举个具体的例子,来说说你想实现什么目的、要求

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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