从两个表更新查询,但有一些例外

时间:2015-04-01 06:07:52

标签: sql sql-server join

Picture(screen shot) http://test.englisheye.co.kr/pic44.jpg

请看上面的图片。

我需要使用T-SQL查询从Table_B更新Table_A。 (带有两个表的普通更新在这里不起作用。)

问题是'4,7''5,3'等值。

我想我需要创建一个函数,但不知道从哪里开始。

请帮帮我。

1 个答案:

答案 0 :(得分:0)

declare @a int, @b nvarchar (20),@c nvarchar (20),@f nvarchar (20),@d int,@e int=1,@g nvarchar(20)
set @b='' set  @c='' set @d =1 set  @f='';

create table #mytable (num nvarchar (20),start nvarchar (20) ,[end] nvarchar (20))

while @e<=(select count(*)from table_b) begin
set @a= (SELECT (len (num)+1)/2 FROM (select ROW_NUMBER () over(order by [start]) as id, * from table_b) a  where id=@e)
while @d<=@a begin
set @b =(SELECT  SUBSTRING(num,2*@d-1,1) FROM (select ROW_NUMBER () over(order by start) as id, * from table_b) a  where id=@e)
set @c +=(select [end] from Table_A where num =cast (@b as int)) +', '
set @f +=(select [end] from Table_A where num =cast (@b as int)) +', '
set @d+=1
end
set @g = ( select num from (select ROW_NUMBER () over(order by [start]) as id, * from table_b) w  where id=@e)
insert into #mytable
select @g, left(@c,case when len(@c)>1 then len(@c)-1  else len(@c) end ) as 'c',
left(@f,case when len(@f)>1 then len(@f)-1  else len(@f) end ) as 'f'

set @b='' set  @c='' set @d =1 set  @f=''
set @e+=1
end

update b 
set b.start =t.start, b.[end]=t.[end] 
from Table_B b
inner join #mytable t on b.num =t.num
drop table #mytable

它有点复杂但对我有用。