sql遍历所有表中某项值为已知数的查询方法

数据库 SQL Server
sql遍历是SQL数据库中重要的一环,下面就将为您介绍下面将为您介绍sql遍历所有表中某项值为已知数的查询语句,希望对您学习SQL数据库有所启迪。

下面将为您介绍sql遍历所有表中某项值为已知数的查询语句写法,供您参考,如果您对sql遍历方面感兴趣的话,不妨一看,希望对您有所帮助。

  1. CREATE proc Full_Search(@string varchar(50))   
  2. as   
  3. begin   
  4.  
  5. declare @tbname varchar(50)   
  6. declare tbroy cursor for select name from sysobjects   
  7. where xtype'u ' --***个游标遍历所有的表   
  8.  
  9. open tbroy   
  10. fetch next from tbroy into @tbname   
  11. while @@fetch_status=0   
  12. begin   
  13.  
  14. declare @colname varchar(50)   
  15. declare colroy cursor for select name from syscolumns   
  16. where id=object_id(@tbname) and xtype in (   
  17. select xtype from systypes   
  18. where name in ( 'varchar ', 'nvarchar ', 'char ', 'nchar ') --数据类型为字符型的字段   
  19. ) --第二个游标是***个游标的嵌套游标,遍历某个表的所有字段   
  20.  
  21. open colroy   
  22. fetch next from colroy into @colname   
  23. while @@fetch_status=0   
  24. begin   
  25.  
  26. declare @sql nvarchar(1000),@j int   
  27. select @sql'select @i=count(1) from ' +@tbname + ' where '+ @colname+ ' like '+ '''%'+@string+ '%'''   
  28. exec sp_executesql @sql,N'@i int output',@i=@j output --输出满足条件表的记录数   
  29. if @j> 0   
  30. BEGIN  
  31. select 包含字串的表名=@tbname  
  32. --exec( 'select distinct '+@colname+' from ' +@tbname + ' where '+ @colname+ ' like '+ '''%'+@string+ '%''')   
  33. END  
  34. fetch next from colroy into @colname   
  35. end   
  36.  
  37. close colroy   
  38. deallocate colroy   
  39.  
  40. fetch next from tbroy into @tbname   
  41. end   
  42. close tbroy   
  43. deallocate tbroy   
  44. end   
  45. go   
  46.  
  47. exec Full_Search '123'   
  48.  

以上就是sql遍历所有表中某项值为已知数的查询方法。

 

 

 

【编辑推荐】

SQL Server安全解析

sql server安全的两层模型

让sqlserver恢复到某个时间点

使用Easy Recovery实现sql server恢复

SQL Server系统表的作用

责任编辑:段燃 来源: 互联网
相关推荐

2009-05-21 09:24:42

表空间查询Oracle

2010-11-25 16:40:11

MySQL大表重复字段

2022-06-21 08:13:34

MySQL查询数据库

2010-11-11 10:53:22

SQL Server遍

2010-10-29 16:48:30

oracle查询所有表

2009-01-27 21:00:00

服务器数据库SQL Server

2012-07-30 09:50:28

MongoDB

2010-09-09 13:32:14

SQL函数遍历

2010-11-09 12:09:23

SQL Server查

2009-06-08 10:20:01

Hibernate查询

2010-11-11 11:00:06

sql server遍

2010-06-10 17:59:05

2009-06-17 15:52:23

Hibernate查询

2010-11-15 16:26:46

Oracle系统时间

2010-10-22 16:48:49

SQL删除所有表数据

2010-10-29 11:22:23

Oracle用户会话

2010-11-11 10:41:03

sql server遍

2010-09-28 10:53:53

SQL表结构

2019-11-15 10:01:07

MySQL数据库数据

2009-06-29 09:03:31

Hibernate多条
点赞
收藏

51CTO技术栈公众号