日期:2014-05-18  浏览次数:20468 次

高手帮忙写一个复杂的Update 语句!
我有如下两个表的内容如下   (A表):
Code         Name             month1       month2         month3       month4       month5       month6
vd0001     HP 50 NULL NULL NULL NULL NULL
vd0002     IBM   60 NULL NULL NULL NULL NULL

B表:
Code         Name             200707     200708       200709       200711
vd0001     HP 50 50 60 60
vd0002     IBM 60 0 0 0

说明:
1。A表的Code   和B表的code   关联。
2。由用户端选择查看供应商的年份和月份(如200707),则A表中的Month1~Month6显示的是连续半年供应商半年的资料。即显示从200707~200712的资料。如果某月份某供应商没有值则显示为0。
3。现在需要用B表中的资料,来更新A表中的(Month1~Month6的值)。

(注用户选择的年份和月份做为一个参数传入,并且显示以它为准后来的6个月的资料。)

这个Update   语句该如何来写呀?请高手帮忙!



------解决方案--------------------
declare @TabA sysname, @TabB sysname --A表和B表
select @TabA = 'AAAA ', @TabB = 'BBBB '

declare @YM varchar(6), @I varchar(2), @sql nvarchar(4000)
select @YM = 200707, @I = 0

declare @Temp table(YM varchar(6))
set nocount on
while @I <6
begin
insert @Temp select (@YM/100+(@YM%100+@I-1)/12)*100+(@YM%100+@I-1)%12+1
set @I=@I+1
end
set nocount off

set @I = 0
select @I=@I+1, @sql = case when b.name is null then coalesce(@sql+ ',a.month ', 'a.month ') + @I + '=0 ' else coalesce(@sql+ ',a.month ', 'a.month ') + @I + '=b.[ ' + b.name + '] ' end from @Temp a left join syscolumns b on a.YM = b.name where b.id = object_id(@TabB)
set @sql = 'update a set ' + @sql + ' from '+ @TabA + ' a join '+ @TabB + ' b on a.Code=b.Code and a.Name=b.Name '
--exec(@sql)
print @sql

select @I = 0, @sql = null
select @I=@I+1, @sql = case when b.name is null then coalesce(@sql+ ',month ', 'month ') + @I + '=0 ' else coalesce(@sql+ ',month ', 'month ') + @I + '=[ ' + b.name + '] ' end from @Temp a left join syscolumns b on a.YM = b.name where b.id = object_id(@TabB)
set @sql = 'insert '+ @TabB + ' select Code,Name, ' + @sql + ' from '+ @TabA
--exec(@sql)
print @sql