SQL Server“偷懒”也能更新数据表

王朝mssql·作者佚名  2006-11-24
宽屏版  字体: |||超大  

问:请专家指教!问题是这样的:我这里有1000个数据表,每个表的结构一模一样(每个表里都有“qq,tj,yj,ej,sj,sij,wj,lj,zs,zjl”10个字段),只是表名不一样。还有一个“数据更新表jj(table_index,qq,tj,yj,ej,sj,sij,wj,lj,zs,zjl)”,除了table_index字段外,同样有“qq,tj,yj,ej,sj,sij,wj,lj,zs,zjl”10个字段,有1000行,该表的用途是用来更新(insert)前述1000个数据表的,即每一行数据更新一个表。但是如果手动更新很麻烦,而且“数据更新表”的内容经常变化,也就是说要经常更新前述的1000个数据表,我就想能否编写个程序,让数据自动进行更新,因此我先将这1000个表的表名放在“表table_index(序号,数据表名)”中,然后编写了如下函数(当中的返回值实际上没有用)。但是语法检查“ @table_name”处有错,不知如何进行更正,或者说这种方法是否可行?如果不可行,请专家能否给我指点一下有什么“偷懒”点的方法进行上述1000个数据表的更新?本人将万分感谢!

use fff

go

create function data_insert1()

RETURNS int

Begin

Declare @qq int(4)

declare @table_index int(4),@tj int(4),@yj int(4),@ej int(4),@sj int(4),@sij bigint(8)

declare @wj bigint(8),@lj bigint(8),@zs bigint(8),@zjl char(15),@table_name char(15)

declare youbiao cursor for select * from jj for read only

open youbiao

fetch next from youbiao into @table_index,@qq,@tj,@yj,@ej,@sj,@sij,@wj,@lj,@zs,@zjl

while @@fetch_status=0 /*loop rows in the cursor*/

begin

declare youbiao_temp cursor for

select 数据表名 from table_index where 序号=@table_index

open youbiao_temp

fetch next from youbiao_temp into @table_name

insert @table_name(qq,tj,yj,ej,sj,sij,wj,lj,zs,zjl)

values(@qihao,@tj,@yj,@ej,@sj,@sij,@wj,@lj,@zs,@zjl)

deallocate youbiao_temp

end

deallocate youbiao

RETURN @table_index

end

go

答:肯定的是,这种方法可行。所犯的错误是没有理解 字段名,表名,数据库名之类作为变量时,必须用动态SQL,使用动态sql语句就能解决该问题.

use fff

go

create function data_insert1()

RETURNS int

Begin

Declare @qq int(4)

declare @table_index int(4),@tj int(4),@yj int(4),@ej int(4),@sj int(4),@sij bigint(8)

declare @wj bigint(8),@lj bigint(8),@zs bigint(8),@zjl char(15),@table_name char(15)

declare youbiao cursor for select 数据库表名,qq,tj,yj,ej,sj,sij,wj,lj,zs,zjl from jj a,table_index b where a.table_index=b.序号 for read only

open youbiao

fetch next from youbiao into @table_name,@qq,@tj,@yj,@ej,@sj,@sij,@wj,@lj,@zs,@zjl

while @@fetch_status=0 /*loop rows in the cursor*/

begin

declare @s Nvarchar(1000)

set @s = 'insert ' + @table_name + '(qq,tj,yj,ej,sj,sij,wj,lj,zs,zjl)' values'+'('+@qq+','+@tj+','+@yj+','+@ej+','+@sj+','+@sij+','+@wj+','+@lj+','+@zs+','+@zjl+')'

Exec(@s)

exec sp_executesql @s

open youbiao

fetch next from youbiao into @table_name,@qq,@tj,@yj,@ej,@sj,@sij,@wj,@lj,@zs,@zjl

end

deallocate youbiao

RETURN 1

end

go

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有