科技行者

行者学院 转型私董会 科技行者专题报道 网红大战科技行者

知识库

知识库 安全导航

至顶网软件频道[SQL Server]“偷懒”也能更新数据表

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

  • 扫一扫
    分享文章到微信

  • 扫一扫
    关注官方公众号
    至顶头条

请专家指教!问题是这样的:我这里有1000个数据表,每个表的结构一模一样(每个表里都有“qq,tj,yj,ej,sj,sij,wj,lj,zs,zjl”10个字段),只是表名不一样。

作者:it专家网 来源:it专家网 2007年9月17日

关键字: 更新 数据库 SQL Server SQL Server 各版本

  • 评论
  • 分享微博
  • 分享邮件
问:请专家指教!问题是这样的:我这里有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

    • 评论
    • 分享微博
    • 分享邮件
    邮件订阅

    如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。

    重磅专题
    往期文章
    最新文章