尝试使用Charindex对文本字段进行子字符串

时间:2016-05-08 16:35:00

标签: sql sql-server sql-server-2008

如何在输液目标率后提取数字:

Substring(SummaryLine, CHARINDEX('n:',summaryline) , 
        LEN(SummaryLine) - CHARINDEX('n:',summaryline)-1) AS NewSumLine  

  , Initial Rate:  40, Goal Rate of Infusion:  55, to goal rate in 8 hours
    , Initial Rate:  40, Goal Rate of Infusion:  60, to goal rate in 8 hours
    , Initial Rate:  30, Goal Rate of Infusion:  30, to goal rate in 8 hours
    , Initial Rate:  30, Goal Rate of Infusion:  30, to goal rate in 8 hours, Dilution:  half strength
    , Initial Rate:  30, Goal Rate of Infusion:  40, to goal rate in 8 hours
    , Initial Rate:  30, Goal Rate of Infusion:  50, 20 ml every 4 hours to goal rate
    , Initial Rate:  50, Goal Rate of Infusion:  50, to goal rate in 8 hours

1 个答案:

答案 0 :(得分:0)

这样的提取在SQL Server中很痛苦。为此,我倾向于使用一系列outer apply s。但是,在您的情况下,所有位置似乎都是固定的,所以我建议:

select substring(summaryline, 43, 2)

如果示例数据不准确,那么如果需要更多工作:

select t2.val
from t outer apply
     (select stuff(t.summaryline, 1, charindex('n:  ', t.summaryline) + 4) as l1
     ) t1 outer apply
     (select left(t1.l1, charindex(',', t1.l1) - 1) as val
     ) t2;

如果summaryline可能不包含该值,则可能需要一些其他条件逻辑。此外,这假设n:足以识别字符串中的位置。