1

重複した行を持つテーブルの列の更新に問題があります..テーブル「tab1」があり、そのデータは次のようになります..

ID col2 col3 col4 col5 col6 col7  
1 xim M gtt tif 1 2  
2 白 M abc png 0 25  
2 白 M abc jpeg 0 25  
3 gtc V ftt gif 4 72  

このテーブルには重複した ID が含まれていますが、col5 のみが異なります。このテーブルには約 4000 行が含まれており、出力が次のようになるように col5 を更新したいと考えています。

ID col2 col3 col4 col5 col6 col7  
1 xim M gtt tif 1 2  
2 白 M abc png,jpeg 0 25  
3 gtc V ftt gif 4 72  

update ステートメントを使用してこのテーブルを更新する方法はありますか? この更新のために一時テーブルを作成する必要がありますか?

4

1 に答える 1

1

njk と Tony が投稿したコメントに同意します。データベースを非正規化するのは良い考えではありませんが、おそらく最終目標はそれほど明白ではなく、特定のニーズに合わせて画像拡張機能を組み合わせることが適切です。

これはあなたが求めていることを行います。関数でカーソルを使用せずにXMLでもそれを行う方法があると確信しています...

use tempdb
go

create table tmp (
  id int, 
  col2 varchar(10), 
  col3 varchar(10), 
  col4 varchar(10), 
  col5 varchar(255), 
  col6 int, 
  col7 int
)
go

insert into tmp values
(1, 'xim', 'M', 'gtt', 'tif', 1, 2),
(2, 'white', 'M', 'abc', 'png', 0, 25),
(2, 'white', 'M', 'abc', 'jpeg', 0, 25),
(2, 'white', 'M', 'abc', 'gif', 0, 25),
(3, 'gtc', 'V', 'ftt', 'jpeg', 4, 72),
(3, 'gtc', 'V', 'ftt', 'tif', 4, 72),
(3, 'gtc', 'V', 'ftt', 'png', 4, 72),
(3, 'gtc', 'V', 'ftt', 'gif', 4, 72)
go

create function fnConcatCol5 (@id int) returns varchar(255) as
begin
  declare @rtn varchar(255) = '', @val varchar(10)

  declare cr cursor local for
    select col5 from tmp where id = @id

  open cr
  fetch next from cr into @val

  while @@fetch_status = 0
  begin
    set @rtn = @rtn + @val + ','
    fetch next from cr into @val
  end

  close cr
  deallocate cr

  set @rtn = left(@rtn, datalength(@rtn) - 1)

  return @rtn
end
go

-- it is more efficient to split up the 'distinct' and function call
-- into separate SQL statements so the function is only run *one* time
-- for each unique id

select distinct id, col2, col3, col4, col6, col7 
into #temp
from tmp

select id, col2, col3, col4, dbo.fnConcatCol5(id) as col5, col6, col7
from #temp
go

drop table tmp, #temp
go
drop function fnConcatCol5
go

返されるデータは次のようになります。

id    col2    col3    col4    col5                col6    col7
----- ------- ------- ------- ------------------- ------- ----
1     xim     M       gtt     tif                 1       2
2     white   M       abc     png,jpeg,gif        0       25
3     gtc     V       ftt     jpeg,tif,png,gif    4       72
于 2012-09-21T19:11:47.893 に答える