SQL中如何根据字段名查找该字段名存在于数据库的哪些表中?
2个回答
展开全部
上处的字段名是指的表中的列名 还是指的 列中某一个 值。
如果是指的列名的话,很简单
select sysobjects.name as tablename,syscolumns.name as columnname
from syscolumns join sysobjects on sysobjects.id = syscolumns.id
where syscolumns.name like '%此处为列名%'
如果是指的一个值的话,要遍历数据库了。如下:
declare@str varchar(100)
set@str='张三'--要搜索的字符串
declare@s varchar(8000)
declaretb cursorlocalfor
selects='if exists(select 1 from ['+b.name+'] where convert(varchar,['+a.name+']) like ''%'+@str+'%'')
print ''select ['+a.name+'] from ['+b.name+']'''
fromsyscolumns a joinsysobjects b ona.id=b.id
whereb.xtype='U'anda.status>=0
--所查列的字段类型
anda.xusertype in(175,239,231,167,56,60,108,106)
opentb
fetchnextfromtb into@s
while @@fetch_status=0
begin
exec(@s)
fetchnextfromtb into@s
end
closetb
deallocatetb
如果是指的列名的话,很简单
select sysobjects.name as tablename,syscolumns.name as columnname
from syscolumns join sysobjects on sysobjects.id = syscolumns.id
where syscolumns.name like '%此处为列名%'
如果是指的一个值的话,要遍历数据库了。如下:
declare@str varchar(100)
set@str='张三'--要搜索的字符串
declare@s varchar(8000)
declaretb cursorlocalfor
selects='if exists(select 1 from ['+b.name+'] where convert(varchar,['+a.name+']) like ''%'+@str+'%'')
print ''select ['+a.name+'] from ['+b.name+']'''
fromsyscolumns a joinsysobjects b ona.id=b.id
whereb.xtype='U'anda.status>=0
--所查列的字段类型
anda.xusertype in(175,239,231,167,56,60,108,106)
opentb
fetchnextfromtb into@s
while @@fetch_status=0
begin
exec(@s)
fetchnextfromtb into@s
end
closetb
deallocatetb
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询