SUBSTRING和CHARINDEX

时间:2016-05-08 22:52:51

标签: sql sql-server

我需要将“输入目标率:###”放入其自己的领域

我正在尝试使用此代码Substring(SummaryLine,CHARINDEX('Infusion:',summaryline),+ 14)但它无效。

, Initial Rate:  40, Goal Rate of Infusion:  0, to goal rate in 8 hours
, Initial Rate:  30, Goal Rate of Infusion:  0, to goal rate in 8 hours
, Initial Rate:  10, Goal Rate of Infusion:  10, to goal rate in 8 hours, HOLD FOR N/V
, Initial Rate:  40, Goal Rate of Infusion:  10, to goal rate in 8 hours
, Initial Rate:  40, Goal Rate of Infusion:  10, to goal rate in 8 hours
, Initial Rate:  100, Goal Rate of Infusion:  100, to goal rate in 8 hours
, Initial Rate:  15, Goal Rate of Infusion:  15, to goal rate in 8 hours
, Initial Rate:  40, Goal Rate of Infusion:  15, to goal rate in 8 hours

1 个答案:

答案 0 :(得分:0)

SELECT
    SummaryLine,
    StartIdx,
    EndIdx,
    CONVERT(
        int,
        SUBSTRING( SummaryLine, StartIdx, EndIdx - StartIdx )
    ) AS InfusionRate
FROM (
    SELECT
        SummaryLine,
        StartIdx,
        CHARINDEX(',', summaryLine, StartIdx) AS EndIdx
    FROM (
        SELECT
            SummaryLine,
            CHARINDEX('Infusion:', SummaryLine) + 10 AS StartIdx,
        FROM
            SourceTable
    )
)

或者作为一行:

SELECT
    CONVERT(
        int,
        SUBSTRING(
            SummaryLine,
            CHARINDEX('Infusion:', summaryLine) + 10,
            CHARINDEX(
                ',',
                SummaryLine,
                CHARINDEX('Infusion:', summaryLine) + 10
            )
        )
    )
FROM
    SourceTable

不允许SQL在单个SELECT语句中缓存或别名表达式结果 - 您需要使用子查询(第一个示例)或重复表达式(第二个示例)。

更新:我做了一些研究,您只能使用CROSS APPLY计算StartIdx一次:

SELECT
    SummaryLine,
    CONVERT(
        int,
        SUBSTRING(
            SummaryLine,
            StartIdx,
            CHARINDEX(',', summaryLine, StartIdx) - StartIdx
        )
    ) AS InfusionRate
FROM
    SourceTable
    CROSS APPLY (
        SELECT CHARINDEX('Infusion:', summaryLine) + 10 AS StartIdx
    )