我有一些數據,如下所示:獲取數SUBSTRING()的SQL Server 2008 R2
AS WRITTEN | UNITS | ROUTINE
TRANSFUSE - RED BLOOD CELLS 1 UNITS ROUTINE, TRANSF... | 1 |
TRANSFUSE - RED BLOOD CELLS 2UNITS ROUTINE, TRAN... | 2 |
TRANSFUSE FRESH FROZEN PLASMA 2 ROUTINE | | 2
TRANSFUSE - RED BLOOD CELLS 2 UNITS ROUTINE, TRAN... | 2 |
TRANSFUSE CRYOPRECIPITATE 10 ROUTINE | | <- 10 SHOULD BE HERE
我使用以下SELECT
語句獲取的值,這可能是粗的方式,但這是我第一次進入SUBSTRING()
CHARINDEX
等。
SELECT語句:
, CASE
WHEN SUBSTRING(SO.DESC_AS_WRITTEN, CHARINDEX('UNIT', SO.DESC_AS_WRITTEN)-2,1) NOT IN (
'1','2','3','4','5','6','7','8','9','10','11'
)
THEN ''
ELSE SUBSTRING(SO.DESC_AS_WRITTEN, CHARINDEX('UNIT', SO.DESC_AS_WRITTEN)-2,1)
END AS [UNITS]
, CASE
WHEN SUBSTRING(SO.DESC_AS_WRITTEN, CHARINDEX('ROUTINE', SO.DESC_AS_WRITTEN)-2,1) NOT IN (
'1','2','3','4','5','6','7','8','9','10','11'
)
THEN ''
ELSE SUBSTRING(SO.DESC_AS_WRITTEN, CHARINDEX('ROUTINE', SO.DESC_AS_WRITTEN)-2,2)
END AS [ROUTINE]
正如上面有10個表示應該顯示ROUTINE
下,在最後一列,但不是我不明白爲什麼。所有其他人似乎都工作得很好。
謝謝
UPDATE 從從@EkriirkE和@GoatCO大的幫助,我用下面的代碼的解決方案:
,(CAST
(ISNULL
(REPLACE
(REPLACE
(REPLACE
(CASE
WHEN PATINDEX('%[0-9]UNIT%',so.desc_as_written) > 0
THEN SUBSTRING(so.desc_as_written,
PATINDEX('%[0-9]UNIT%',so.desc_as_written)-1,2)
WHEN PATINDEX('%[0-9] UNIT%',so.desc_as_written) > 0
THEN SUBSTRING(so.desc_as_written,
PATINDEX('%[0-9] UNIT%',so.desc_as_written)-1,2)
WHEN PATINDEX('%[0-9]ROUTINE%',so.desc_as_written) > 0
THEN SUBSTRING(so.desc_as_written,
PATINDEX('%[0-9]ROUTINE%',so.desc_as_written)-1,2)
WHEN PATINDEX('%[0-9] ROUTINE%',so.desc_as_written) > 0
THEN SUBSTRING(so.desc_as_written,
PATINDEX('%[0-9] ROUTINE%',so.desc_as_written)-1,2)
WHEN PATINDEX('%[0-9]STAT%',so.desc_as_written) > 0
THEN SUBSTRING(so.desc_as_written,
PATINDEX('%[0-9]STAT%',so.desc_as_written)-1,2)
WHEN PATINDEX('%[0-9] STAT%',so.desc_as_written) > 0
THEN SUBSTRING(so.desc_as_written,
PATINDEX('%[0-9] STAT%',so.desc_as_written)-1,2)
WHEN PATINDEX('%[0-9]TODAY%',so.desc_as_written) > 0
THEN SUBSTRING(so.desc_as_written,
PATINDEX('%[0-9]TODAY%',so.desc_as_written)-1,2)
WHEN PATINDEX('%[0-9] TODAY%',so.desc_as_written) > 0
THEN SUBSTRING(so.desc_as_written,
PATINDEX('%[0-9] TODAY%',so.desc_as_written)-1,2)
END,
'S',''),
'T',''),
'U','')
, 0)
AS INT)
) AS [TEST]
謝謝你,我必須玩弄它,因爲我得到以下錯誤'轉換失敗時,將varchar值's1'轉換爲數據類型int.' –
@MCP_infiltrator它可能是,你有一種情況,像'CELLS1'這樣的'REPLACE()'語句包裝這些空間可能是解決這個問題的最簡單方法。 –
我將不得不在REPLACE()上做一些閱讀,因爲你的回答是我第一次遇到它。感謝您的幫助 –