将MSSQL函数转换为MySQL

时间:2014-01-31 11:11:17

标签: mysql sql-server

我无法将以下MSSQL函数转换为MySQL。

MSSQL

USE [EkoPayroll]
GO
/****** Object:  UserDefinedFunction [dbo].[fn_GetLowestOf3]    Script Date: 01/31/2014 13:52:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER   FUNCTION [dbo].[fn_GetLowestOf3] (
    @num1 numeric,
    @num2 numeric,
    @num3 numeric
 )  
RETURNS numeric AS  
BEGIN
    declare @num numeric
    set @num=@num1
    IF @num2<@num1
    SET @num=@num2 

    IF @num3<@num
    SET @num=@num3

    RETURN @num
END

的MySQL

DELIMITER $$

CREATE
    /*[DEFINER = { user | CURRENT_USER }]*/
    FUNCTION `eko_payroll`.`GetLowestOf3`(num1 numeric,
    num2 numeric,
    num3 numeric)
    RETURNS 
    /*LANGUAGE SQL
    | [NOT] DETERMINISTIC
    | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
    | SQL SECURITY { DEFINER | INVOKER }
    | COMMENT 'string'*/
numeric
    BEGIN
declare num numeric
    set num=num1
    IF num2<num1
    SET num=num2 

    IF num3<num
    SET num=num3

    RETURN num
    END$$

DELIMITER ;

我收到错误

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 'set num=num1
    IF num2<num1
    SET num=num2 
    IF num3<num
    SET num=num3

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

我认为您错过了THENEND IF关键字

仔细查看指定的语法IF Syntax

类似

CREATE

    FUNCTION `GetLowestOf3`(num1 numeric,
    num2 numeric,
    num3 numeric)
    RETURNS 
numeric
BEGIN
    declare num numeric;
    set num=num1;
    IF num2<num1 THEN
      SET num=num2 ;
    END IF;

    IF num3<num THEN
      SET num=num3;
    END IF;

    RETURN num;
END

SQL Fiddle DEMO

您也可以尝试

CREATE

    FUNCTION `GetLowestOf3`(num1 numeric,
    num2 numeric,
    num3 numeric)
    RETURNS 
numeric
BEGIN
    declare num numeric;
    SET num = 
    (
      SELECT MIN(Val)
      FROM 
            (
              SELECT num1 Val
              UNION ALL
              SELECT num2
              UNION ALL
              SELECT num3
             ) t
     );

    RETURN num;
END

SQL Fiddle DEMO

MySQL有一个LEAST function

  

使用两个或多个参数,返回最小(最小值)参数。

SELECT LEAST(3,2,1)