2016-10-19 89 views
0

我正在嘗試編寫一個函數,它需要兩個參數並返回基於case語句的計算結果(請參見下文)。我不斷收到一個語法錯誤:函數中的SQL Case語句

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CASE when (medToConvert) = "Codeine" then MME = doseToConver' at line 13

這是我到目前爲止已經試過:

/* Function that takes two parameters as input: 
    Dosage of an opioid 
    Name of the opioid 

    Returns the morphine equivalent dosage */ 

    CREATE FUNCTION convertToMorphineEquiv (doseToConvert INT, medToConvert VARCHAR(20)) 
    RETURNS INT 

    BEGIN 
     DECLARE MME INT 

     CASE  
       when (medToConvert) = "Codeine" then MME = doseToConvert * 0.15 

       -- Fentanyl Transdermal (in mcg/hr) 
       when (medToConvert) = "Fentanyl" then MME = doseToConvert * 2.4 

       when (medToConvert) = "Hydrocodone" then MME = doseToConvert * 1 
       when (medToConvert) = "Hydromorphone" then MME = doseToConvert * 4 
       when (medToConvert) = "Methadone" AND doseToConvert BETWEEN 1 AND 20 then MME = doseToConvert * 4 
       when (medToConvert) = "Methadone" AND doseToConvert BETWEEN 21 AND 40 then MME = doseToConvert * 8 
       when (medToConvert) = "Methadone" AND doseToConvert BETWEEN 41 AND 60 then MME = doseToConvert * 10 
       when (medToConvert) = "Methadone" AND doseToConvert >=60 then MME = doseToConvert * 12 
       when (medToConvert) = "Morphine" then MME = doseToConvert * 1 
       when (medToConvert) = "Oxycodone" then MME = doseToConvert * 1.5 
       when (medToConvert) = "Oxymorphone" then MME = doseToConvert * 3 
       when (medToConvert) = "Tapentadol" then MME = doseToConvert * 0.4 

       else "Conversion for this opioid is not available" 
     END 

     RETURN MME 
    END 
+0

你得到了什麼錯誤? – Mureinik

+1

另外 - 你使用了什麼[標籤:rdbms]? – Mureinik

+0

請編輯您的問題,並添加**確切的**錯誤信息 –

回答

0

創建一個表來代替,並加入到它。使用CROSS APPLY操作可以獲得更快的性能,因爲標量值用戶定義的函數遭受RBAR(Row By Agonizing Row)性能損失。

CREATE TABLE dbo.MedicineDoseConversion (
    medicine_name varchar(20) not null, 
    dose_to_convert_min_units int null, 
    dose_to_convert_max_units int null, 
    dosage_multiplier decimal(18,10) not null 
) 
GO 

INSERT dbo.MedicineDoseConversion (medicine_name, dose_to_convert_min_units, 
dose_to_convert_max_units, dosage_multiplier) 
SELECT 'Codeine', null, null, 0.15 UNION ALL 
SELECT 'Fentanyl', null, null, 2.4 UNION ALL 
SELECT 'Hydrocodone', null, null, 1 UNION ALL 
SELECT 'Hydromorphone', null, null, 4 UNION ALL 
SELECT 'Methadone', 1, 20, 4 UNION ALL 
SELECT 'Methadone', 21, 40, 8 UNION ALL 
SELECT 'Methadone', 41, 60, 10 UNION ALL 
SELECT 'Methadone', 60, null, 12 UNION ALL 
SELECT 'Morphine', null, null, 1 UNION ALL 
SELECT 'Oxycodone', null, null, 1.5 UNION ALL 
SELECT 'Oxymorphone', null, null, 3 
; 
GO