MS SQL SERVER 全库搜索
程序员文章站
2022-05-02 21:35:59
...
定位单个数据库中等于某值的记录所在的表和列。 第13行的xtype=167代表只搜索数据类型是varchar的列。 第18行就是根据关键字具体过滤列的数据。 SQL Server create proc global_search@key varchar(2000)asdeclare tab_cursor cursor for select name from s
定位单个数据库中等于某值的记录所在的表和列。
第13行的xtype=167代表只搜索数据类型是varchar的列。
第18行就是根据关键字具体过滤列的数据。
create proc global_search @key varchar(2000) as declare tab_cursor cursor for select name from sysobjects where type = 'U' declare @sql nvarchar(2000) declare @tab_name nvarchar(100) declare @col_name nvarchar(100) declare @row_count int open tab_cursor fetch next from tab_cursor into @tab_name while(@@fetch_status = 0) begin declare col_cursor cursor for select name from syscolumns where id = OBJECT_ID(@tab_name) and xtype = 167 open col_cursor fetch next from col_cursor into @col_name while(@@fetch_status = 0) begin set @sql = 'declare row_cursor cursor for select count(*) from ' + @tab_name + ' where ' + @col_name + ' like ''%' + @key + '%''' exec(@sql) open row_cursor fetch next from row_cursor into @row_count if @row_count > 0 print @tab_name + '.' + @col_name close row_cursor deallocate row_cursor fetch next from col_cursor into @col_name end close col_cursor deallocate col_cursor fetch next from tab_cursor into @tab_name end close tab_cursor deallocate tab_cursor
create proc global_search @key nvarchar(2000) as declare @sql nvarchar(2000) declare @tab_name nvarchar(100) declare @col_name nvarchar(100) declare @row_count int declare @has_cursor int declare @col_cursor cursor declare @tab_cursor cursor set @tab_cursor = cursor for select name from sysobjects where type = 'U' open @tab_cursor fetch next from @tab_cursor into @tab_name while(@@fetch_status = 0) begin set @col_cursor = cursor for select name from syscolumns where id = OBJECT_ID(@tab_name) and xtype = 231 and length > 13 open @col_cursor fetch next from @col_cursor into @col_name while(@@fetch_status = 0) begin set @sql = N'select count(*) from ' + @tab_name + ' where ' + @col_name + ' = ''%' + @key + '%''' exec sp_executesql @sql, N'@row_count int', @row_count if @row_count > 0 print @tab_name + '.' + @col_name fetch next from @col_cursor into @col_name end if cursor_status('local', '@col_cursor') > -1 close @col_cursor if cursor_status('local', '@col_cursor') > -3 deallocate @col_cursor fetch next from @tab_cursor into @tab_name end if cursor_status('local', '@tab_cursor') > -1 close @tab_cursor if cursor_status('local', '@tab_cursor') > -3 deallocate @tab_cursor
推荐阅读
-
C#实现连接SQL Server2012数据库并执行SQL语句的方法
-
SQL Server数据库开发的二十一条法则
-
SQL Server 数据库的备份详细介绍及注意事项
-
C#连接到sql server2008数据库的实例代码
-
SQL Server数据库的高性能优化经验总结
-
将MS SQL SERVER数据库运行在普通用户(独立用户)状态下的设置方法终结篇
-
SQL Server 2005/2008 用户数据库文件默认路径和默认备份路径修改方法
-
SQL Server 出现Error: 1326错误(管理器无法连接远程数据库)问题解决方案
-
卸载VS2011 Developer Preview后Sql Server2008 R2建立数据库关系图报“找不到指定的模块”错误的解决方法
-
SQL Server中通过扩展存储过程实现数据库的远程备份与恢复