sqlserver2008查找某数据库中的列是否存在某个值

创建存储过程spFind_Column_In_DB,根据参数@type区分搜索数值或文字类型的列,通过游标遍历用户表,构造并执行SQL查询是否存在指定值(@str),将结果存入临时表#tbl。最后返回临时表中的结果,可用于查找数据库中包含特定值的列。
摘要由CSDN通过智能技术生成
--2008查找某数据库中的列是否存在某个值
create proc spFind_Column_In_DB
(
@type int,--类型:1为文字类型、2为数值类型
@str nvarchar(100)--需要搜索的名字
)
as
--创建临时表存放结果
create table #tbl(PK int identity primary key ,tbl sysname,col sysname)
declare @tbl nvarchar(300),@col sysname,@sql nvarchar(1000)
if @type=1
begin
declare curTable cursor fast_forward
for
select '['+SCHEMA_NAME(SCHEMA_ID)+'].['+o.name+']' tableName,'['+c.name+']' columnName from sys.columns c inner join sys.objects o on c.object_id=o.object_id
where o.type_desc='user_table' and user_type_id in (167,175,231,239,35,99)
end
else
begin
declare curTable cursor fast_forward
for
select '['+SCHEMA_NAME(SCHEMA_ID)+'].['+o.name+']' tableName,'['+c.name+']' columnName from sys.columns c inner join sys.objects o on c.object_id=o.object_id
where o.type_desc='user_table' and user_type_id in (56,48,52,59,60,62,106,108,122)
end
open curtable
fetch next from curtable into @tbl,@col
while @@FETCH_STATUS=0
begin
set @sql='if exists (select * from '+@tbl+' where '
if @type=1
begin
set @sql += @col + ' like ''%'+@str +'%'')'
end
else
begin
set @sql +=@col + ' in ('+@str+'))'
end

set @sql += ' INSERT #TBL(tbl,col) VALUES('''+@tbl+''','''+@col+''')'
--print @sql
exec (@sql)
fetch next from curtable into @tbl,@col
end
close curtable
deallocate curtable
select * from #tbl

--使用例子,查询库中存在aaa这个值的列:
exec spFind_Column_In_DB 1,'aaa'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值