Search code examples
sqlmysqlfunctionmysql-error-1064

Syntax Error in Create Function


This is one of the more confusing functions I've attempted. The logic works within a select statement, but I can't seem to create a user-defined function.

Here's the error:

"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 'delimiter$$ create function checkdate ( p_datetimestamp varchar (6) ) retur' at line 1"

Here's the code: (Changing a text string 'yymmdd' into date format. '100810' becomes 2010-09-01 per the logic.)

delimiter$$
create function `checkdate` (
 p_datetimestamp varchar (6)
 )
 returns date

begin
declare ret_val date;
set ret_val = 
   str_to_date(
 concat(
  /*Assign Year -> %y*/
    if(
    mid(p_datetimestamp,3,2) = '12',
    (left(p_datetimestamp,2) + 1),
    left(p_datetimestamp,2)
    ),
  /*Assign Month -> %m*/
    if(
    (mid(p_datetimestamp,3,2) >= '01' and mid(p_datetimestamp,3,2) <= '11'),
    concat('0', (mid(p_datetimestamp,3,2) + 1)), '01'
    ),
  /*Assign Date -> %d*/
    if(
    (mid(p_datetimestamp,5,2) >= '01' and mid(p_datetimestamp,5,2) <= '16'), '01', '17'
    ),
 ), 
    '%y%m%d');
return ret_val;
end$$

Solution

  • A rogue comma right at the end

    DELIMITER $$
    
    create function `checkdate` (
     p_datetimestamp varchar (6)
     )
     returns date
    
    begin
    declare ret_val date;
    set ret_val = 
       str_to_date(
     concat(
      /*Assign Year -> %y*/
        if(
        mid(p_datetimestamp,3,2) = '12',
        (left(p_datetimestamp,2) + 1),
        left(p_datetimestamp,2)
        ),
      /*Assign Month -> %m*/
        if(
        (mid(p_datetimestamp,3,2) >= '01' and mid(p_datetimestamp,3,2) <= '11'),
        concat('0', (mid(p_datetimestamp,3,2) + 1)), '01'
        ),
      /*Assign Date -> %d*/
        if(
        (mid(p_datetimestamp,5,2) >= '01' and mid(p_datetimestamp,5,2) <= '16'), '01', '17'
        ) /*<-- Comma Removed from Here*/
     ), 
        '%y%m%d');
    return ret_val;
    end$$