[SQL Server]“偷懒”也能更新数据表
来源:it专家网
作者:Webmaster
时间:2007-04-23
点击:
[ 收藏] [ 投稿]
问:请专家指教!问题是这样的:我这里有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 |
如果您对本文有任何疑问或者建议,请到讨论区发表您的意见:
>>
论坛入口 <<
上一篇: [SQL Server]探讨SQL2000对XML的支持 下一篇: [SQL Server] 2005数据库开发详解
【文章评论】
【收藏本文】
【推荐好友】
【打印本文】
【我要投稿】 【论坛讨论】
更多相关文章
|
|