0

I am attempting to create a function in MySQL that will return a value based on the presence of specific strings in a field. My select statement will ultimately need to make this evaluation many times so I wanted to create a function for efficiency purposes. Here is my code:

create function [dbname].id_datasource
(descval varchar(100))
returns varchar(10)  
begin  
        declare datasource varchar(10) default ''  
        select datasource =   
            case when descval like 'CLT%' or descval like '%CLT%' then 'CLT'  
            when descval like 'PCB%' or descval like '%PCB%' then 'PCB'  
            else 'NA' end   
        return (datasource)  
end  

I get this error:

SQL Error [1064] [42000]: 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 'select datasource = case when descval like 'CLT%' or descval like '%CLT%' th' at line 6

note: it requires me to enter a db name prefix for my function - it returns 'no database selected' without it - I did substitute my long database name for [dbname] above.

muncieharts
  • 13
  • 1
  • 5

1 Answers1

1

You have syntax problems:

  1. Missing ; at the end of each statement.
  2. Use SET to assign a variable.
DELIMITER $$

create function [dbname].id_datasource (descval varchar(100))
returns varchar(10)
begin  
        declare datasource varchar(10) default '';
        SET datasource =   
            case 
                when descval like '%CLT%' then 'CLT'  
                when descval like '%PCB%' then 'PCB'  
                else 'NA' 
            end; 
        return datasource;
end
$$

DELIMITER ;

There's no need to have both LIKE 'CLT%' and LIKE '%CLT%', since anything that matches CLT% will also match %CLT%.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Not sure what I was thinking on CLT% vs %CLT% - thanks. On the query itself, I still get an error - just at an earlier spot: SQL Error [1064] [42000]: 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 '.id_datasource (descval varchar(100)) returns varchar(10) begin dec' at line 1 – muncieharts Jan 21 '22 at 23:16
  • Sounds like a problem with the way you entered the database name before the function name. – Barmar Jan 21 '22 at 23:18
  • You nailed it. I was including database and specific table. That worked. Thanks much. – muncieharts Jan 21 '22 at 23:31
  • BTW, you can set the default database using `USE databasename;` – Barmar Jan 21 '22 at 23:32