sql server - TSQL Replicate row n times based on data -
sql server - TSQL Replicate row n times based on data -
given table fields id, qty, code , row in table info
id qty code 1 3 a,b,c
i alter in database be
id qty code 1 1 2 1 b 3 1 c
is there easy tsql this?
create split function create function [dbo].[split] ( @delimited nvarchar(max), @delimiter nvarchar(100) ) returns @t table (id int identity(1,1), val nvarchar(max)) begin declare @xml xml set @xml = n'<t>' + replace(@delimited,@delimiter,'</t><t>') + '</t>' insert @t(val) select r.value('.','varchar(max)') item @xml.nodes('/t') records(r) homecoming end
test data declare @table table (id int, qty int, code varchar(100)) insert @table values (1, 3 , 'a,b,c'), (2, 4 , 'e,f,g,h,h')
query select t.id ,count(*) qty ,c.val code @table t cross apply dbo.split(t.code, ',')c grouping t.id ,c.val
result ╔════╦═════╦══════╗ ║ id ║ qty ║ code ║ ╠════╬═════╬══════╣ ║ 1 ║ 1 ║ ║ ║ 1 ║ 1 ║ b ║ ║ 1 ║ 1 ║ c ║ ║ 2 ║ 1 ║ e ║ ║ 2 ║ 1 ║ f ║ ║ 2 ║ 1 ║ g ║ ║ 2 ║ 2 ║ h ║ ╚════╩═════╩══════╝
sql-server tsql
Comments
Post a Comment