我有一个药房表,药房ID和方案如下;将组合列值分解为不同的行
PharmacyID Regimen
140646 3TC/D4T/EFV
140653 ABC/D4T/NVP
我的愿望是得到这样的事情;
PharmacyID Regimen
140646 3TC
140646 D4T
140646 EFV
140653 ABC
140653 D4T
140653 NVP
我坚持在谷歌上搜索我还没有尝试过任何解决方案
我有一个药房表,药房ID和方案如下;将组合列值分解为不同的行
PharmacyID Regimen
140646 3TC/D4T/EFV
140653 ABC/D4T/NVP
我的愿望是得到这样的事情;
PharmacyID Regimen
140646 3TC
140646 D4T
140646 EFV
140653 ABC
140653 D4T
140653 NVP
我坚持在谷歌上搜索我还没有尝试过任何解决方案
这将有工作,通过XML的即时字符串分割的方法:
DECLARE @tbl TABLE(PharmacyID INT,Regimen VARCHAR(100));
INSERT INTO @tbl VALUES(140646,'3TC/D4T/EFV')
,(140653,'ABC/D4T/NVP');
WITH Casted AS (
SELECT PharmacyID
,CAST('<x>' + REPLACE((SELECT Regimen AS [*] FOR XML PATH('')),'/','</x><x>') + '</x>' AS XML) AS TheXML
FROM @tbl
)
SELECT PharmacyID
,a.x.value(N'(./text())[1]','nvarchar(max)') AS Regimen
FROM Casted
CROSS APPLY Casted.TheXML.nodes(N'/x') AS A(x)
create function [dbo].[udf_splitstring] (@tokens varchar(max),
@delimiter varchar(5))
returns @split table (
token varchar(200) not null)
as
begin
declare @list xml
select @list = cast('<a>'
+ replace(@tokens, @delimiter, '</a><a>')
+ '</a>' as xml)
insert into @split
(token)
select ltrim(t.value('.', 'varchar(200)')) as data
from @list.nodes('/a') as x(t)
return
end
CREATE TABLE #Table111
([PharmacyID] int, [Regimen] varchar(11))
;
INSERT INTO #Table111
([PharmacyID], [Regimen])
VALUES
(140646, '3TC/D4T/EFV'),
(140653, 'ABC/D4T/NVP')
;
select [PharmacyID], token FROM #Table111 as t1
CROSS APPLY [dbo].UDF_SPLITSTRING([Regimen],'/') as t2
输出
PharmacyID token
140646 3TC
140646 D4T
140646 EFV
140653 ABC
140653 D4T
140653 NVP
create table #temp1(string1 varchar(max))
Insert into #temp1
Values('3TC/D4T/EFV'),('ABC/D4T/NVP')
SELECT
Replace(Replace(CAST(Tbl.Col.query('.') as varchar(max)),'<a>',''),'</a>','')
FROM
(Select cast('<a>'+ replace(string1, '/', '</a><a>') + '</a>' as xml)as t
from #temp1) tl
Cross apply
tl.t.nodes('/a') AS Tbl(Col)
你在使用MySQL,MS SQL Server或Postgresql吗?答案不会是一样的... – jarlh
我正在使用MS SQL –
使用字符串拆分函数(如在公认的答案中)不是一个坏主意,但有更好的方法[在这里:Aaron Bertrand关于String Splitters]( https://sqlperformance.com/2012/07/t-sql-queries/split-strings) – Shnugo