我有药物的定义栏。我希望将定义分为[product name(PN)]
,[doseform(DF)]
,[total dose(TD)]
和[units]
。
例如:
BENADRYL: MYLANTA 1:1 SOLUTION(Benadryl mylanta(PN),Sol(DF),1:1(TD),NULL(units))
MASK AND SPACER (Mark and Spacer(PN),NUll,NUll,NUll)
BL VITAMIN B-6 50 MG TABS(BL Vitamin(PN),Tabs(DF),50(TD),MG(Units))
答案 0 :(得分:1)
我对您的数据做了一些假设。 1是第一个开口括号开始定义即。在定义之前,名称中没有括号。我也假设产品定义结构不会改变。
所以,为了得到你的答案,我使用了一个修改过的分裂字符串函数。我用这个作为基础:T-SQL split string
这里的区别是该函数将返回一个2列表,以便我们可以识别定义部分
CREATE FUNCTION dbo.splitstring_custom
(
@stringToSplit VARCHAR(MAX)
)
RETURNS @returnList TABLE
(
[Type] [nvarchar](20)
,[Name] [nvarchar](500)
)
AS
BEGIN
DECLARE @name NVARCHAR(255)
DECLARE @pos INT
DECLARE @colidx INT = 1
WHILE CHARINDEX(',', @stringToSplit) > 0
BEGIN
SELECT @pos = CHARINDEX(',', @stringToSplit)
SELECT @name = SUBSTRING(@stringToSplit, 1, @pos - 1)
INSERT INTO @returnList
SELECT CASE WHEN @colidx = 1 THEN 'Product Name'
WHEN @colidx = 2 THEN 'Dose Form'
WHEN @colidx = 3 THEN 'Total Dose'
WHEN @colidx = 4 THEN 'Units'
END
,@name
SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos + 1, LEN(@stringToSplit) - @pos)
SET @colidx += 1
END
INSERT INTO @returnList
SELECT CASE WHEN @colidx = 1 THEN 'Product Name'
WHEN @colidx = 2 THEN 'Dose Form'
WHEN @colidx = 3 THEN 'Total Dose'
WHEN @colidx = 4 THEN 'Units'
END
,@stringToSplit
RETURN
END
然后我们使用一些字符串操作得到定义的相关部分:
SUBSTRING(medication, CHARINDEX('(', medication) + 1, LEN(medication) - (CHARINDEX('(', medication) + 1))
然后PIVOT将结果展平:
DECLARE @t TABLE (id varchar(20), medication varchar(100))
INSERT INTO @t VALUES ('BENADRYL', 'BENADRYL: MYLANTA 1:1 SOLUTION(Benadryl mylanta(PN),Sol(DF),1:1(TD),NULL(units))')
INSERT INTO @t VALUES ('MASK', 'MASK AND SPACER (Mark and Spacer(PN),NULL,NULL,NULL)')
INSERT INTO @t VALUES ('BL VITAMIN', 'BL VITAMIN B-6 50 MG TABS(BL Vitamin(PN),Tabs(DF),50(TD),MG(Units))')
SELECT id, [Product Name], [Dose Form], [Total Dose], [Units]
FROM (SELECT id, Type, Name
FROM @t t
CROSS APPLY dbo.splitstring_custom(SUBSTRING(medication, CHARINDEX('(', medication) + 1, LEN(medication) - (CHARINDEX('(', medication) + 1)))
) X PIVOT ( MAX(Name) FOR TYPE IN ([Product Name], [Dose Form], [Total Dose], [Units]) ) pvt