sql遍歷所有表中某項值為已知數的查詢方法
作者:佚名
sql遍歷是SQL數據庫中重要的一環,下面就將為您介紹下面將為您介紹sql遍歷所有表中某項值為已知數的查詢語句,希望對您學習SQL數據庫有所啟迪。
下面將為您介紹sql遍歷所有表中某項值為已知數的查詢語句寫法,供您參考,如果您對sql遍歷方面感興趣的話,不妨一看,希望對您有所幫助。
- CREATE proc Full_Search(@string varchar(50))
- as
- begin
- declare @tbname varchar(50)
- 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(50)
- 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 ') --數據類型為字符型的字段
- ) --第二個游標是***個游標的嵌套游標,遍歷某個表的所有字段
- open colroy
- fetch next from colroy into @colname
- while @@fetch_status=0
- begin
- declare @sql nvarchar(1000),@j int
- select @sql= 'select @i=count(1) from ' +@tbname + ' where '+ @colname+ ' like '+ '''%'+@string+ '%'''
- exec sp_executesql @sql,N'@i int output',@i=@j output --輸出滿足條件表的記錄數
- if @j> 0
- BEGIN
- select 包含字串的表名=@tbname
- --exec( 'select distinct '+@colname+' from ' +@tbname + ' where '+ @colname+ ' like '+ '''%'+@string+ '%''')
- END
- fetch next from colroy into @colname
- end
- close colroy
- deallocate colroy
- fetch next from tbroy into @tbname
- end
- close tbroy
- deallocate tbroy
- end
- go
- exec Full_Search '123'
以上就是sql遍歷所有表中某項值為已知數的查詢方法。
【編輯推薦】
責任編輯:段燃
來源:
互聯網