从字符串中提取第一个可用数字及其后续文本

时间:2014-06-18 17:25:58

标签: sql sql-server tsql

我必须从字符串中提取剂量和计量单位。 一个字符串可以包含非常相似的模式,但我只需要提取字符串中的第一个数字,其后跟一个剂量。

例如:

  

止痛药。 20 mg / 100 mL NS(0.2mg / mL)治疗:IV PCA成人/   限定符:标准连续速率= 0毫克/小时,静脉注射,常规PCA剂量=   0.4mg

我需要提取 20 作为剂量," mg" 作为Select语句中的度量单位。

有什么想法吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE Table1
    ([dosage] varchar(144))
;

INSERT INTO Table1
    ([dosage])
VALUES
    ('Pain Medication. 20 mg/100 mL NS (0.2mg/mL) 
      Therapy: IV PCA Adult / Qualifier: Standard Continuous Rate = 0 mg/hr, 
      IV, Routine PCA Dose = 0.4 mg')
;

查询1

SELECT substring(dosage,
                 PATINDEX('%[0-9]%',dosage),
                 PATINDEX('%/%',dosage)-PATINDEX('%[0-9]%',dosage)
                )
FROM Table1

<强> Results

| COLUMN_0 |
|----------|
|    20 mg |

答案 1 :(得分:1)

- 架构

CREATE TABLE script
    (
     id int identity primary key, 
     details varchar(200)
    );

INSERT INTO script
(details)
VALUES
('Pain Medication. 20 mg/100 mL NS (0.2mg/mL) Therapy: IV PCA Adult / Qualifier: Standard Continuous Rate = 0 mg/hr, IV, Routine PCA Dose = 0.4 mg'),
('Pain Medication. 300 mg/100 mL NS (0.2mg/mL) Therapy: IV PCA Adult / Qualifier: Standard Continuous Rate = 0 mg/hr, IV, Routine PCA Dose = 0.4 mg');

- 剂量

SELECT 
SUBSTRING(
SUBSTRING(
  details,PATINDEX('%[0-9]%',details), 
  (select (PATINDEX('%[/]%',details)-PATINDEX('%[0-9]%',details)))), 
  0, PATINDEX('%[ ]%',SUBSTRING(
  details,PATINDEX('%[0-9]%',details), 
  (select (PATINDEX('%[/]%',details)-PATINDEX('%[0-9]%',details)))))) as [Dosage]
 from script

- 单位

SELECT 
SUBSTRING(
SUBSTRING(
  details,PATINDEX('%[0-9]%',details), 
  (select (PATINDEX('%[/]%',details)-PATINDEX('%[0-9]%',details)))), 
  PATINDEX('%[ ]%',SUBSTRING(
  details,PATINDEX('%[0-9]%',details), 
  (select (PATINDEX('%[/]%',details)-PATINDEX('%[0-9]%',details))))),
3) as [Units]
 from script

SQL小提琴:http://sqlfiddle.com/#!6/4e0b6/38

答案 2 :(得分:0)

已经给出了优雅的答案,但这也可以使用LEFT和RIGHT函数在没有子串函数的情况下完成。

DECLARE @Mytext AS VARCHAR(200)
SET @Mytext = 'Pain Medication. 20 mg/100 mL NS (0.2mg/mL) 
      Therapy: IV PCA Adult / Qualifier: Standard Continuous Rate = 0 mg/hr, 
      IV, Routine PCA Dose = 0.4 mg'

SELECT LEFT(RIGHT(@Mytext, LEN(@Mytext) - (PATINDEX('%[0-9]%',@Mytext)-1)), 
        PATINDEX('%/%',RIGHT(@Mytext, LEN(@Mytext) 
        - (PATINDEX('%[0-9]%',@Mytext)-1)-1)))

结果:

20 mg