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