在一个数据库中的所有表里查找一个字符串

此TSQL语句是针对SQL Server 2012编写。如果使用之前版本,需要对部分语句进行重写。

 1 USE [数据库名称];
 2 
 3 --1.定义需要查找的关键字。在搜索中,使用模糊搜索:LIKE '%@key_find%'
 4 DECLARE @key_find NVARCHAR(MAX) = '123';--假设是找字符串"123"
 5 
 6 --2.用游标Cursor_Table,遍历所有表
 7 DECLARE Cursor_Table CURSOR FOR
 8     SELECT name from sysobjects WHERE xtype = 'u' AND name <> 'dtproperties';
 9 OPEN Cursor_Table;
10 DECLARE @tableName NVARCHAR(MAX);
11 FETCH NEXT from Cursor_Table INTO @tableName;
12 WHILE @@fetch_status = 0
13 BEGIN
14     DECLARE @tempSQLText NVARCHAR(MAX) = '';
15 
16     --3.在表中,用游标columnCursor,遍历所有字段。注意,只遍历字符串类型的字段(列)
17     DECLARE columnCursor CURSOR FOR 
18         SELECT Name FROM SysColumns WHERE ID = Object_Id( @tableName ) and
19                                                                             ( 
20                                                                                 xtype = 35 or --text
21                                                                                 xtype = 99 or --ntext
22                                                                                 xtype = 167 or --varchar
23                                                                                 xtype = 175 or --char
24                                                                                 xtype = 231 or --nvarchar
25                                                                                 xtype = 239 or --nchar
26                                                                                 xtype = 241 --xml
27                                                                             )
28     OPEN columnCursor;
29     DECLARE @columnName NVARCHAR(MAX);
30     FETCH NEXT from columnCursor INTO @columnName;
31     WHILE @@fetch_status = 0
32     BEGIN
33 
34         --4.在表的字段中,对每一行进行模糊搜索,并输出找到的信息。
35         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';
36         EXEC( @DynamicSQLText );
37         FETCH NEXT from columnCursor INTO @columnName
38     END
39     exec(@tempSQLText);
40     CLOSE columnCursor;
41     DEALLOCATE columnCursor;
42     FETCH NEXT from Cursor_Table INTO @tableName;
43 END
44 CLOSE Cursor_Table;
45 DEALLOCATE Cursor_Table;

 

转载于:https://www.cnblogs.com/xxxteam/archive/2013/03/12/2955582.html

你可能感兴趣的:(在一个数据库中的所有表里查找一个字符串)