top
Loading...
“偷懶”也能更新數據表

 

問:請專家指教!問題是這樣的:我這里有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

作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗