top

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

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

复制代码
--SQL2008查找某数据库中的列是否存在某个值
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'
复制代码

 

本文版权归作者所有,未经作者同意不得转载。

posted @   桦仔  阅读(13384)  评论(1编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示