单个数据库多张表的操作

有时候我们做统计需要给每个店铺动态创建一张表用来统计访问数据,但是随着时间推移,到时候我们有可能需要给这些表添加一个字段或是查询数据什么的。

表在实际项目中会多达上千张。

我之前有写了一些sql语句在这边分享一下。

1. 给所有的表添加一个字段IsFacebook字段。这边是操作735张表。

 1 declare @i int select @i=1 
2 declare @sql varchar(100)
3 declare @tableName varchar(50)
4 while @i <= 735
5 begin
6 set @tableName = 'VisitLog' + cast(@i as varchar(50))
7 set @sql = 'alter table ' + @tableName + ' add IsFacebook bit default 0 NOT NULL'
8 if exists(select * from sysobjects where name = @tableName)
9 exec(@sql)
10
11 set @i=@i+1
12 end

2. 查询所有表中记录数最多的店铺ID。这边是假设操作1700张表。

 1 declare @i int select @i=1
2 declare @shopId int select @shopId=1
3 declare @count int
4 declare @maxCount int select @maxCount =0
5 declare @sql nvarchar(50)
6 declare @tableName nvarchar(50)
7
8 while @i <=1700
9 begin
10
11 set @tableName = 'VisitLog' + cast(@i as nvarchar(50))
12 set @sql = 'select @count = count(*) from ' + @tableName
13
14 if exists(select * from sysobjects where name = @tableName)
15 begin
16 exec sp_executesql @sql,N'@count int output', @count output
17 if @count > @maxCount
18 begin
19 set @maxCount = @count
20 set @shopId = @i
21 end
22 end
23
24 set @i=@i+1
25 end
26
27 print @maxCount
28 print @shopId


我想有了上面这两个写法,做其他操作只要稍微做下改动代码就可以了。

不知道其他人做类似的事情也是不是写sql语句来执行还是有其他工具可以完成?

posted @ 2011-09-30 22:45  Timothy  阅读(2184)  评论(6编辑  收藏  举报