sqlÖÐifÓï¾äµÄÓ÷¨
sql if Óï¾äÓÃÓÚƾ֤Ìõ¼þÖ´ÐÐÌض¨²Ù×÷¡£ÆäÓ﷨Ϊ£ºif Ìõ¼þ then ±í´ïʽ1 [elsif Ìõ¼þ then ±í´ïʽ2]… [else ±í´ïʽn] end if;ËüÔÊÐíÄú»ùÓÚÌõ¼þ¶¯Ì¬ÐÞ¸ÄÅÌÎÊ»ò²Ù×÷£¬ÀýÈçÑ¡ÔñÌض¨ÁС¢Ö´ÐÐÅÌËã»ò¸üÐÂ/²åÈëÊý¾Ý¡£×î¼Ñʵ¼ù°üÀ¨¼á³ÖÌõ¼þ¼òÆÓ¡¢×èֹǶÌ× if Óï¾ä¡¢Ê¹Óà elsif ºÍÈ·±£Ê¼ÖÕ°üÀ¨ else ×Ӿ䡣
SQL ÖÐ IF Óï¾ä
SQL IF Óï¾äÓÃÓÚÔÚÖª×ãÌض¨Ìõ¼þʱִÐÐÖ¸¶¨µÄ²Ù×÷¡£ÆäÓï·¨ÈçÏ£º
IF Ìõ¼þ THEN ±í´ïʽ1 [ELSIF Ìõ¼þ THEN ±í´ïʽ2] ... [ELSE ±í´ïʽN] END IF;
µÇ¼ºó¸´ÖÆ
ÆäÖУº
Ìõ¼þ£ºÖ¸¶¨ÒªÆÀ¹ÀµÄÌõ¼þ¡£
±í´ïʽ£ºÒªÖ´ÐеIJÙ×÷£¨ÈôÊÇÌõ¼þΪÕ棩¡£
ELSIF£ºÓÃÓÚÖ¸¶¨ÆäËûÌõ¼þºÍÏìÓ¦²Ù×÷¡£
ELSE£ºÓÃÓÚÖ¸¶¨ÈôÊÇËùÓÐÌõ¼þ¶¼²»ÎªÕæʱҪִÐеIJÙ×÷¡£
Ó÷¨
IF Óï¾äÔÊÐíÄú»ùÓÚÌض¨Ìõ¼þ¶¯Ì¬µØÐÞ¸Ä SQL ÅÌÎÊ»ò²Ù×÷¡£ÀýÈ磬Ëü¿ÉÓÃÓÚ£º
ÔÚÖª×ãÌض¨Ìõ¼þʱѡÔñ²î±ðµÄÁС£
ƾֵ֤µÄ²î±ðÖ´Ðвî±ðµÄÅÌËã¡£
ƾ֤Ìõ¼þ¸üлò²åÈëÊý¾Ý¡£
ʾÀý
¼ÙÉèÎÒÃÇÓÐÒ»¸öÃûΪ “Customers” µÄ±í£¬ÆäÖаüÀ¨ÒÔÏÂÁУº
CustomerID
CustomerName
CustomerType
ÎÒÃÇ¿ÉÒÔʹÓà IF Óï¾äÀ´Ñ¡Ôñƾ֤¿Í»§ÀàÐÍ»ñÈ¡²î±ðµÄÁУº
SELECT CASE WHEN CustomerType = 'Individual' THEN CustomerName WHEN CustomerType = 'Business' THEN CustomerName || ' (Business)' END AS CustomerName FROM Customers;
µÇ¼ºó¸´ÖÆ
×î¼Ñʵ¼ù
ʹÓà IF Óï¾äʱ£¬Çë×ñÕÕÒÔÏÂ×î¼Ñʵ¼ù£º
¼á³ÖÌõ¼þ¼òÆÓÇÒÒ×ÓÚÃ÷È·¡£
×èֹǶÌ×Ì«¶àµÄ IF Óï¾ä£¬Õâ»áʹ´úÂëÄÑÒÔ¶ÁÈ¡¡£
ʹÓà ELSIF ×Ó¾ä¶ø²»ÊǶà¸ö IF Óï¾äÀ´´¦Àí¶à¸öÌõ¼þ¡£
È·±£Ê¼ÖÕ±£´æÒ»¸ö ELSE ×Ó¾äÀ´´¦ÀíËùÓпÉÄܵÄÌõ¼þ¡£
ÒÔÉϾÍÊÇsqlÖÐifÓï¾äµÄÓ÷¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡