程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> 其他數據庫知識 >> MSSQL >> sql server 2012 數據庫一切內外查找某字符串的辦法

sql server 2012 數據庫一切內外查找某字符串的辦法

編輯:MSSQL

sql server 2012 數據庫一切內外查找某字符串的辦法。本站提示廣大學習愛好者:(sql server 2012 數據庫一切內外查找某字符串的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是sql server 2012 數據庫一切內外查找某字符串的辦法正文



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. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved