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 --第一个游标遍历所有的表   
  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 @sqlselect @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遍历所有表中某项值为已知数的查询方法  。