Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a table-valued function in mysql

Tags:

sql

mysql

I'm migrating from SqlServer 2008 to MySql and I have a lot of stored procedure that use a generic table-value function that split a varchar. The sqlserver function declaration is:

CREATE FUNCTION [dbo].[fnSplit](
    @sInputList VARCHAR(8000)       -- List of delimited items
  , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item varchar(50))

/* SAMPLE
select * from fnSplit('12 345 67',' ')
select * from fnSplit('12##34#5##67','##')
*/

BEGIN

    DECLARE @sItem VARCHAR(8000)

    WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
    BEGIN
        SELECT  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
@sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

        IF LEN(@sItem) > 0 
            INSERT INTO @List SELECT @sItem
    END 

    IF LEN(@sInputList) > 0
        INSERT INTO @List SELECT @sInputList -- Put the last item in

    RETURN
END
like image 666
AutoCiudad Avatar asked Jul 05 '26 18:07

AutoCiudad


1 Answers

For splitting a string specifically, these existing Stack Exchange answers helped me:

  • How to split a string, using a numbers table: https://stackoverflow.com/a/17942691/795690

  • How to avoid needing a numbers table, by using a 'generator': https://stackoverflow.com/a/9751493/795690

And for the more generic question:

  • How to return tables from one stored procedure to another, by writing to known-named temporary tables (which are, at least, unique per-connection): https://dba.stackexchange.com/a/270887/61926
like image 180
MikeBeaton Avatar answered Jul 07 '26 08:07

MikeBeaton