0

我有药物的定义栏。我希望将定义拆分为[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))
4

1 回答 1

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
于 2013-08-21T23:52:22.430 回答