我有一个sql server 2005的数据库,里面有大约一百多个表,是一个网站的后台数据库。
我想请教大家:怎样用一条Sql 语句,把这一百多个表中,每个表中含有@163.com的字段检索出来,也就是想知道所有163电子邮箱的内容检索出来。
一百多个表的结构都不是完全相同的。其中某个表的结构示例如下:
col1 col2 col3 webmail email add
jack 18 2600 arlg@163.com XXX 北京市东城区
rose 24 rose@163.com jack@163.com XYZ 北京市景山区
john 22 2700 nodress nonumber noadd
kate 163.com 2800 adf sdfs sdfsss
halo 32 hlo@yaho.com kkk kkkkk 长春某某
检索结果如下:
col1 col2 col3 webmail email add
jack 18 2600 arlg@163.com XXX 北京市东城区
rose 24 rose@163.com jack@163.com XYZ 北京市景山区
所有表 字符串
------解决方案--------------------
这是2008上可以执行的,不知道2005能不能执行,先给你试试吧:
第一步,创建存储过程:
CREATE proc spFind_Column_In_DB
(
@type int,--类型:1为文字类型、2为数值类型
@str nvarchar(100)--需要搜索的名字
)
as
--创建临时表存放结果
create table #tbl(PK int identity primary key ,tbl sysname,col sysname)
declare @tbl nvarchar(300),@col sysname,@sql nvarchar(1000)
if @type=1
begin
declare curTable cursor fast_forward
for
select '['+SCHEMA_NAME(SCHEMA_ID)+'].['+o.name+']' tableName,'['+c.name+']' columnName from sys.columns c inner join sys.objects o on c.object_id=o.object_id
where o.type_desc='user_table' and user_type_id in (167,175,231,239,35,99)
end
else
begin
declare curTable cursor fast_forward
for
select '['+SCHEMA_NAME(SCHEMA_ID)+'].['+o.name+']' tableName,'['+c.name+']' columnName from sys.columns c inner join sys.objects o on c.object_id=o.object_id
where o.type_desc='user_table' and user_type_id in (56,48,52,59,60,62,106,108,122)
end
open curtable
fetch next from curtable into @tbl,@col
while @@FETCH_STATUS=0
begin
set @sql='if exists (select * from '+@tbl+' where '
if @type=1
begin
set @sql += @col + ' like ''%'+@str +'%'')'
end
else
begin
set @sql +=@col + ' in ('+@str+'))'
end
set @sql += ' INSERT #TBL(tbl,col) VALUES('''+@tbl+''','''+@col+''')'
--print @sql
exec (@sql)
fetch next from curtable into @tbl,@col
end
close curtable
deallocate curtable
select * from #tbl
第二步:执行:
EXEC spFind_Column_In_DB 1,'@163.com'
------解决方案--------------------
是这样吗:
select t.name as table_name,
c.name as column_name,
c.column_id