加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 09:53:33 所属栏目:MsSql教程 来源:网络整理
导读:div class="codetitle" a style="CURSOR: pointer" data="30671" class="copybut" id="copybut30671" onclick="doCopy('code30671')" 代码如下:div class="codebody" id="code30671" USE [数据库名称];--1.定义需要查找的关键字。在搜索中,使用模糊搜索:LI

<div class="codetitle"><a style="CURSOR: pointer" data="30671" class="copybut" id="copybut30671" onclick="doCopy('code30671')"> 代码如下:<div class="codebody" id="code30671">
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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读