以下のカンマ区切りのデータを使って列方向のデータを結合したテーブルを作りたいです。
※使用しているものは SQL Server 2012 です。
【カンマ区切りデータ】
declare @IDs varchar(100) = '1,2,3'--商品ID
declare @Quantities varchar(100) = '10,20,30'--上記商品IDに対応する数
【最終的に欲しいテーブル】
商品ID | 数 |
---|---|
1 | 10 |
2 | 20 |
3 | 30 |
【やったこと】
カンマ区切りデータから2つのテーブルを作る(カンマ区切り -> テーブル にする関数を作成)
※下記、上手く表示できておりませんが。。。
商品ID |
---|
1 |
2 |
3 |
数 |
---|
10 |
20 |
30 |
レコード数分のループを回して、各テーブルのループ数分のレコードを取得して、
その結果をインサートする方法は思いついたのですが、もっとスマートな方法があるだろうと思い質問しました。
※列同士がくっつけばいいだけなのに。。。
declare @IDs varchar(100) = '1,2,3'--商品ID
declare @Quantities varchar(100) = '10,20,30'--上記商品IDに対応する数
declare @TID table (nID int)
declare @TQuantity table (nQuantity int)
declare @TOrder table (
nID int,
nQuantity int
)
insert into @TID
select cast(A.str as int) from カンマ区切り -> テーブル にする関数 as A
declare @CountID int = (select count(*) from @TID)
insert into @TQuantity
select cast(B.str as int) from カンマ区切り -> テーブル にする関数 as B
declare @CountQuantity int = (select count(*) from @TQuantity)
if @CountID <> @CountQuantity
begin
--error
select 'error'
end
declare @Count int = 1
while @Count <= @CountID
begin
insert into @TOrder values ( (select nID from ( select nID, row_number() over (order by nID) as RowNumID from @TID ) as C where RowNumID = @Count), (select nQuantity from ( select nQuantity, row_number() over (order by nQuantity) as RowNumQuantity from @TQuantity ) as D where RowNumQuantity = @Count) ) set @Count = @Count + 1
end
-- 最終的に欲しい形にはなったが・・・
select * from @TOrder

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/03/09 00:46