简体   繁体   中英

SQL Else If statement to return text value from numeric value of another column - not working

I need to have a calculated column Site_Condition that will return a text value based on the numeric value of another column Condition_Score which is in the same table.

Below is what I have tried inserting into the Computed Column Specification, I but get this message:

Error validating the formula

I have also tried creating it from script "Create table as" using same syntax below ie: Site_Condition AS (IF....)

What am I doing wrong?

IF([Condition_Score]<0.51,'Very poor',(ELSE  
IF([Condition_Score]<1.51,'Poor', ELSE 
IF([Condition_Score]<2.51,'Moderate',ELSE 
IF([Condition_Score]<3.51,'Good',ELSE 
IF([Condition_Score]>3.51,'Excellent'))))))

In SQL, we use CASE rather than IF

CASE WHEN [Condition_Score]<0.51 THEN 'Very poor'
     WHEN [Condition_Score]<1.51 THEN 'Poor'
     WHEN [Condition_Score]<2.51 THEN 'Moderate'
     WHEN [Condition_Score]<3.51 THEN 'Good' 
     ELSE 'Excellent' END

But for completeness, here's the IIF() version (note the extra " I ", short for "Immediate If"):

IIF([Condition_Score]<0.51, 'Very poor',
    IIF([Condition_Score]<1.51, 'Poor',
    IIF([Condition_Score]<2.51, 'Moderate',
    IIF([Condition_Score]<3.51,'Good',
        'Excellent'))))

If I recall correctly, IIF() is not available until Sql Server 2016.

These also fix a bug whereby if the score was exactly 3.51 the result would be NULL .

This is Simple way to ...perform your Query...

DECLARE @Condition_Score AS DECIMAL
SET @Condition_Score=1.25

DECLARE @Message AS VARCHAR(50)


IF(@Condition_Score<0.51)
BEGIN
    SET @Message ='Very poor'
END

else IF(@Condition_Score<1.51)
BEGIN
    SET @Message ='poor'
END

ELSE IF(@Condition_Score<2.51)
BEGIN
    SET @Message ='Moderate'
END

ELSE IF (@Condition_Score<3.51)
BEGIN
    SET @Message ='Good'
END

ELSE IF(@Condition_Score>3.51)
BEGIN
    SET @Message='Excellent'
END

PRINT @Message

Note:-Here " PRINT @Message" for Checking the Current Output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM