Guest User

Untitled

a guest
Feb 19th, 2018
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. /**
  2. * This sample demonstrates how to return the results
  3. * of a CASE statement in a short way without wrapping
  4. * it into BEGIN/END, declaring and setting variables
  5. * and returning the result at the end.
  6. *
  7. * Author: Jan Beilicke <dev@jotbe-fx.de>
  8. * Date: 2011-07-06
  9. */
  10. DROP FUNCTION IF EXISTS caseTestShort;
  11. DELIMITER //
  12.  
  13. CREATE FUNCTION caseTestShort(str VARCHAR(10))
  14. RETURNS VARCHAR(10) DETERMINISTIC
  15. CASE str
  16. WHEN 'foo' THEN
  17. RETURN 'bar';
  18. WHEN 'bla' THEN
  19. RETURN 'fasel';
  20. ELSE
  21. RETURN 'Not found';
  22. END CASE;
  23. //
  24.  
  25. DELIMITER ;
  26.  
  27. SELECT
  28. caseTestShort('foo') AS foo,
  29. caseTestShort('bla') AS bla,
  30. caseTestShort('bar') AS bar;
  31.  
  32. /**
  33. * The long form in comparison
  34. */
  35.  
  36. DROP FUNCTION IF EXISTS caseTestLong;
  37. DELIMITER //
  38.  
  39. CREATE FUNCTION caseTestLong(str VARCHAR(10))
  40. RETURNS VARCHAR(10) DETERMINISTIC
  41. BEGIN
  42.  
  43. DECLARE res VARCHAR(10);
  44.  
  45. CASE str
  46. WHEN 'foo' THEN
  47. SET res = 'bar';
  48. WHEN 'bla' THEN
  49. SET res = 'fasel';
  50. ELSE
  51. SET res = 'Not found';
  52. END CASE;
  53.  
  54. RETURN res;
  55. END
  56. //
  57.  
  58. DELIMITER ;
  59.  
  60. SELECT
  61. caseTestLong('foo') AS foo,
  62. caseTestLong('bla') AS bla,
  63. caseTestLong('bar') AS bar;
Add Comment
Please, Sign In to add comment