SQL2008查詢某資料庫中的某個值是否存在

mug發表於2021-09-09

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'

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/506/viewspace-2800658/,如需轉載,請註明出處,否則將追究法律責任。

相關文章