sqlÖеÄifÓï¾äÔõÑù¶à´ÎÅжÏ
sql ÖпÉÒÔʹÓôøÓÐ then ºÍ else Òªº¦×ֵĶà¸öÌõ¼þÀ´¾ÙÐжà´ÎÅжϣ¬ÈçÏ£ºif condition1 then — Óï¾ä¿é 1elsif condition2 then — Óï¾ä¿é 2…else — Óï¾ä¿é nend if;
SQL ÖÐʹÓà IF Óï¾ä¾ÙÐжà´ÎÅжÏ
IF Óï¾äÊÇ SQL ÖÐÓÃÓÚƾ֤Ìõ¼þÖ´Ðвî±ð²Ù×÷µÄ¿ØÖÆÁ÷Óï¾ä¡£ÔÚijЩÇéÐÎÏ£¬ÐèÒªÔÚµ¥¸ö IF Óï¾äÖоÙÐжà´ÎÅжϲŻªÈ·¶¨ÒªÖ´ÐеIJÙ×÷¡£
Óï·¨
ʹÓà THEN ºÍ ELSE Òªº¦×Ö½«¶à¸öÌõ¼þÁ´½Óµ½ IF Óï¾ä£º
IF condition1 THEN -- Óï¾ä¿é 1 ELSIF condition2 THEN -- Óï¾ä¿é 2 ... ELSE -- Óï¾ä¿é n END IF;
µÇ¼ºó¸´ÖÆ
Àý×Ó
¼ÙÉèÎÒÃÇÓÐÒ»¸ö±í students£¬ÆäÖаüÀ¨Ñ§ÉúµÄЧ¹û¡£ÎÒÃÇÐèÒªÅÌÎÊѧÉúµÄЧ¹û£¬²¢Æ¾Ö¤Ð§¹ûµÄ²î±ð¹æÄ£·ÖÅÉÆ·¼¶£º
SELECT name, score, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' WHEN score >= 70 THEN 'C' ELSE 'F' END AS grade FROM students;
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬CASE Óï¾ä±»ÓÃÀ´Æ¾Ö¤Ñ§ÉúµÄЧ¹û¾ÙÐжà´ÎÅжϡ£Ã¿¸ö WHEN ×Ó¾äÖ¸¶¨Ò»¸öÌõ¼þºÍÒ»¸ö¶ÔÓ¦µÄÆ·¼¶¡£ELSE ×Ó¾äÌṩһ¸öĬÈÏÆ·¼¶£¬ÔÚËùÓÐÆäËûÌõ¼þ¶¼²»Öª×ãʱʹÓá£
×¢ÖØ:
ELSEIF Òªº¦×ÖÊÇ¿ÉÑ¡µÄ£»ÈôÊÇûÓÐ ELSEIF Ìõ¼þ£¬Ôò¿ÉÒÔÊ¡ÂÔ¡£
ÿ¸ö WHEN ×Ó¾ä±ØÐèÒÔ THEN Òªº¦×Ö×îºó£¬¶ø ELSE ×Ó¾ä±ØÐèÒÔ END IF Òªº¦×Ö×îºó¡£
CASE Óï¾äÒ²¿ÉÒÔÓÃÓÚ¾ÙÐжà´ÎÅжϣ¬²¢ÇÒÔÚijЩÇéÐÎϸü¿ÉÈ¡¡£
ÒÔÉϾÍÊÇsqlÖеÄifÓï¾äÔõÑù¶à´ÎÅжϵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡