SQL Server多表搜索字符串
我们前面介绍了一些关于SQL Server 的很多文章,今天我们主要介绍一下SQL Server下在不知道表名的情况下进行搜索字符串,我们都知道,在一个数据库下会有多张表单的时候,我们所要查找的内容不知道在哪个表单中,那怎么办呢?今天我们就通过编写SQL 语句来解决这个问题;
我们DB4数据库下测试创建了两张表,分别插入了一些数据;具体见下表;
我们测试在两张表中都插入了一条相同的数据,在uname字段中搜索zs这个字符串;
我们编写的SQL 语句;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
declare @string varchar(30)
set @string = 'zs' --替换为要查找的字符串
DECLARE @tabName VARCHAR(40),@colName VARCHAR(40) DECLARE @sql VARCHAR(2000) declare @tsql varchar(8000)
DECLARE tabCursor CURSOR FOR SELECT name from sysobjects WHERE xtype = 'u' AND name <> 'dtproperties'
OPEN tabCursor FETCH NEXT from tabCursor INTO @tabName WHILE @@fetch_status = 0 BEGIN set @tsql = ''
DECLARE colCursor CURSOR FOR Select Name from SysColumns Where id =Object_Id(@tabName) and xtype=167
OPEN colCursor FETCH NEXT from colCursor INTO @colName WHILE @@fetch_status = 0 BEGIN SET @sql = 'if(exists(select * from ' + @tabName + ' where '
SET @sql = @sql + @colName + ' like ' '%' + @string + '%' ')) begin select * from '
set @sql = @sql + @tabName + ' where ' + @colName + ' like ' '%' + @string + '%' ';select ' ''
+ @tabName + '' ' as TableName end'
set @tsql = @tsql + @sql + ';'
FETCH NEXT from colCursor INTO @colName END exec (@tsql)
CLOSE colCursor DEALLOCATE colCursor FETCH NEXT from tabCursor INTO @tabName END CLOSE tabCursor DEALLOCATE tabCursor |
执行后,会显示执行结果;
搜索的字符串显示列信息及表信息;
结构zs字符串在info表中第一列,然后通过在tb_info表中的第一行中
本文转自 高文龙 51CTO博客,原文链接:http://blog.51cto.com/gaowenlong/1968181,如需转载请自行联系原作者