2016-10-19 2 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

- [tag : rdbms]는 무엇을 사용하고 있습니까? – Mureinik

+0

질문을 편집하고 ** 정확한 ** 오류 메시지를 추가하십시오 –

답변

0

대신 테이블을 작성하고, 조인 나는 구문 오류가 계속. 스칼라 값 사용자 정의 함수는 RBAR (Row By Agonizing Row) 성능 저하로 인해 CROSS APPLY 연산을 사용하여 훨씬 빠른 성능을 얻을 수 있습니다.

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