sql server 2012 数据库所有表里查找某字符串的方法

2022-05-24 0 642

复制代码 代码如下:

USE [数据库名称];

 –1.定义需要查找的关键字。在搜索中,使用模糊搜索:LIKE ‘%@key_find%’

 DECLARE @key_find NVARCHAR(MAX) = ‘123’;–假设是找字符串”123″

 –2.用游标Cursor_Table,遍历所有表

 DECLARE Cursor_Table CURSOR FOR

     SELECT name from sysobjects WHERE xtype = ‘u’ AND name <> ‘dtproperties’;

 OPEN Cursor_Table;

 DECLARE @tableName NVARCHAR(MAX);

 FETCH NEXT from Cursor_Table INTO @tableName;

 WHILE @@fetch_status = 0

 BEGIN

     DECLARE @tempSQLText NVARCHAR(MAX) = ”;

     –3.在表中,用游标columnCursor,遍历所有字段。注意,只遍历字符串类型的字段(列)

     DECLARE columnCursor CURSOR FOR

         SELECT Name FROM SysColumns WHERE ID = Object_Id( @tableName ) and

                                                                             (

                                                                                 xtype = 35 or –text

                                                                                 xtype = 99 or –ntext

                                                                                 xtype = 167 or –varchar

                                                                                 xtype = 175 or –char

                                                                                 xtype = 231 or –nvarchar

                                                                                 xtype = 239 or –nchar

                                                                                 xtype = 241 –xml

                                                                             )

     OPEN columnCursor;

     DECLARE @columnName NVARCHAR(MAX);

     FETCH NEXT from columnCursor INTO @columnName;

     WHILE @@fetch_status = 0

     BEGIN

         –4.在表的字段中,对每一行进行模糊搜索,并输出找到的信息。

         DECLARE @DynamicSQLText NVARCHAR(MAX) = ‘IF ( EXISTS ( SELECT * FROM [‘ + @tableName + ‘] WHERE [‘ + @columnName + ‘] LIKE ”%’ + @key_find + ‘%” ) ) BEGIN DECLARE @CurrentTableCount Bigint = ( SELECT COUNT(*) From [‘ + @tableName + ‘] ); PRINT ”Find : Table [‘ + @tableName + ‘], Column [‘ + @columnName + ‘], Row Count:” + CAST( @CurrentTableCount AS NVARCHAR(MAX) ) + ”.”;  END’;

         EXEC( @DynamicSQLText );

         FETCH NEXT from columnCursor INTO @columnName

     END

     exec(@tempSQLText);

     CLOSE columnCursor;

     DEALLOCATE columnCursor;

     FETCH NEXT from Cursor_Table INTO @tableName;

 END

 CLOSE Cursor_Table;

 DEALLOCATE Cursor_Table;

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 MsSql sql server 2012 数据库所有表里查找某字符串的方法 https://www.niceym.com/61238.html