您好我的批量插入问题。
挑战/目标是将具有逗号分隔符的列保存到具有不同ID's的另一个表
例如 - >
我从@temp table
Rolln FullName
441246 John Doe,Jane More,John Spade
441248 Jose Mendez,Ali Muhm,Jacob Stile
保存在人员表中
结果将在插入People->
People_ID RollNumber FullName
1 441246 John Doe
2 441246简更多
3 441246约翰·斯佩德
我创建的脚本重复名称为
INSERT @Temp_Original
select rollnumber,
case when CHARINDEX(',',FullName)>0
then SUBSTRING(FullName,1,CHARINDEX(',',FullName)-1)
else FullName end FullName,
CASE WHEN CHARINDEX(',',FullName)>0
THEN REPLACE(SUBSTRING(FullName,CHARINDEX(',',FullName)+1,len(FullName)), ',', '')
ELSE NULL END as FullName2,
CASE WHEN CHARINDEX(',',FullName)>0
THEN REPLACE(SUBSTRING(FullName,CHARINDEX(',',FullName)+1,len(FullName)), ',', '')
ELSE NULL END as FullName3,
[Address], Code, Place, [Country], LegalTxt
from (
select newrec.RollNumber, newrec.FullName, newrec.[Address], newrec.Code, newrec.Place, newrec.Country, newrec.LegalTxt
from [dbo].[view_FinanceCompare] newrec
left join [dbo].[view_MainCompare] oldrec
on newrec.RollNumber = oldrec.rollnumber
where oldrec.rollnumber is null
) t
--Print 'Insert to people'
Insert [dbo].[dbo_People] ([FullName], [CreatedOn], [CreatedBy])
Select Fullname, getdate(), rollnumber
From @Temp_Original
UNION
Select Fullname2, getdate(), rollnumber
From @Temp_Original Where FullName2<>''
UNION
Select Fullname3, getdate(), rollnumber
From @Temp_Original Where FullName3<>''
你的帮助大多受到赞赏。
答案 0 :(得分:0)
你可以用递归cte来做。这是一个例子:
create table t(id int, n nvarchar(max))
Insert into t values
(1, 'a,b,c'),
(2, 'e,f,g')
; with cte as (
Select
Id,
N,
substring(n, 1, charindex(',', n)-1) as name,
Charindex(',',n) as p
From t
Union all
Select id, n, substring(n, p+1, charindex(',', n, p)-1),
Charindex(',', n, p+1)
From cte
Where p <> 0
)
Select id, namename from cte
Order by id, name