教您使用SQL游標解決查詢?nèi)韱栴}
作者:佚名
已知一個字符串,去查詢整個數(shù)據(jù)庫中有哪些表里包含這個字符串,應(yīng)該如何實現(xiàn)呢?下文中使用SQL游標解決了這個難題。
借助SQL游標,可以輕松解決SQL查詢?nèi)淼膯栴}。下面就為您介紹該SQL游標的寫法,供您參考,希望對您學(xué)習SQL游標有所幫助。
- Create procedure Full_Search(@string varchar(100))
- as
- begin
- declare @tbname varchar(100)
- declare tbroy cursor for select name from sysobjects
- where xtype='u' --***個游標遍歷所有的表
- open tbroy
- fetch next from tbroy into @tbname
- while @@fetch_status=0
- begin
- declare @colname varchar(100)
- declare colroy cursor for select name from syscolumns
- where id=object_id(@tbname) and xtype in (
- select xtype from systypes
- where name in ('varchar','nvarchar','char','nchar') --數(shù)據(jù)類型為字符型的字段
- ) --第二個游標是***個游標的嵌套游標,遍歷某個表的所有字段
- open colroy
- fetch next from colroy into @colname
- while @@fetch_status=0
- begin
- declare @sql nvarchar(4000),@j int
- select @sql='select @i=count(1) from ' +quotename(@tbname) +' where '+ quotename(@colname)+' like '+'''%'+@string+'%'''
- exec sp_executesql @sql,N'@i int output',@i=@j output --輸出滿足條件表的記錄數(shù)
- if @j>0
- begin
- declare @v varchar(8000)
- set @v='select distinct '+quotename(@colname)+' from ' +quotename(@tbname) +' where '+ quotename(@colname)+' like '+'''%'+@string+'%'''
- exec(@v)
- end
- fetch next from colroy into @colname
- end
- close colroy
- deallocate colroy
- fetch next from tbroy into @tbname
- end
- close tbroy
- deallocate tbroy
- end
- exec Full_Search '市場'
- drop proc Full_Search
【編輯推薦】
責任編輯:段燃
來源:
互聯(lián)網(wǎng)