MYSQL: a self-written string manipulation function returns an unexpected result

I am trying to implement the MYSQL function MY_LEFT_STR (STRING x, position INT) so that

  • MY_LEFT_STR ('HELLO', 4) => returns 'HELL' (same as the internal LEFT function)
  • MY_LEFT_STR ('HELLO', - 1) => returns 'HELL'

DROP FUNCTION IF EXISTS MY_LEFT_STR;
CREATE FUNCTION MY_LEFT_STR(
  in_str VARCHAR(255),
  pos INT
)
RETURNS VARCHAR(255)
BEGIN
  IF (pos < 0) THEN 
      RETURN LEFT(in_str,LENGTH(in_str) - pos);
  ELSE          
    RETURN LEFT(in_str,pos);  
  END IF;           
END;

result

select left_str('HELLO', 4)            as A
     , left_str('HELLO',-1)            as B
     , left('HELLO',length('HELLO')-1) as C
from dual

+-----+-----+-----+
| A   | B   | C   |
+-----+-----+-----+
|HELL |HELLO|HELL | 
+-----+-----+-----+

QUESTION What happened to the declaration of my function? (Besides the general lack of testing for bordercases like MY_LEFT_STR ('A', - 4) ...


ANSWER : so confusing ... the answer is double negative for pos = -1 in

RETURN LEFT(in_str,LENGTH(in_str) - pos); 

it should be

RETURN LEFT(in_str,LENGTH(in_str) + pos);
+3
2

: LENGTH(in_str) - (-1)?

pos , LENGTH(in_str) - pos , . LEFT() , , .

+2
RETURN LEFT(in_str,LENGTH(in_str) - pos);

pos , LENGTH (in_str) - pos ( ):

LENGTH(HELLO) - (-1) = 6?
+2

Source: https://habr.com/ru/post/1715605/


All Articles