欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

sql server 2012 數(shù)據(jù)庫所有表里查找某字符串的方法

 更新時(shí)間:2013年03月12日 14:22:49   作者:  
此TSQL語句是針對(duì)SQL Server 2012編寫。如果使用之前版本,需要對(duì)部分語句進(jìn)行重寫。
復(fù)制代碼 代碼如下:

USE [數(shù)據(jù)庫名稱];

 --1.定義需要查找的關(guān)鍵字。在搜索中,使用模糊搜索:LIKE '%@key_find%'
 DECLARE @key_find NVARCHAR(MAX) = '123';--假設(shè)是找字符串"123"

 --2.用游標(biāo)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.在表中,用游標(biāo)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.在表的字段中,對(duì)每一行進(jìn)行模糊搜索,并輸出找到的信息。
         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;

相關(guān)文章

最新評(píng)論