这是我的代码:
IF EXISTS(SELECT * FROM User WHERE Username = @Username) THEN
RETURN -1;
ELSEIF EXISTS(SELECT * FROM User WHERE Email = @Email)
THEN
RETURN -2;
ELSE
INSERT INTO User(Username, Password, Email)
VALUES ('Nicki',@Password,@Email);
RETURN LAST_INSERT_ID();
END IF
还有一张图片
但是该函数不会插入值-您能解释为什么吗?
最佳答案
@Username
是9.4 User-Defined Variables,Username
是表列。
另外,请检查:C.1 Restrictions on Stored Programs::Name Conflicts within Stored Routines。
尝试:
mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.18 |
+-----------+
1 row in set (0.00 sec)
mysql> DROP FUNCTION IF EXISTS `InsertUser`;
Query OK, 0 rows affected (0.00 sec)
mysql> DROP TABLE IF EXISTS `User`;
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE IF NOT EXISTS `User`(
-> `Id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
-> `Username` VARCHAR(255) NOT NULL,
-> `Password` VARCHAR(255) NOT NULL,
-> `Email` VARCHAR(255) NOT NULL
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER //
mysql> CREATE FUNCTION `InsertUser`(`_Username` VARCHAR(255),
-> `_Email` VARCHAR(255),
-> `_Password` VARCHAR(255)
-> )
-> RETURNS INT
-> LANGUAGE SQL
-> DETERMINISTIC
-> MODIFIES SQL DATA
-> BEGIN
-> IF EXISTS(SELECT * FROM `User` WHERE `Username` = `_Username`) THEN
-> RETURN -1;
-> ELSEIF EXISTS(SELECT * FROM `User` WHERE `Email` = `_Email`) THEN
-> RETURN -2;
-> ELSE
-> INSERT INTO `User` (`Username`, `Password`, `Email`)
-> VALUES ('Nicki', `_Password`, `_Email`);
-> RETURN LAST_INSERT_ID();
-> END IF;
-> END//
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> SELECT
-> `Id`,
-> `Username`,
-> `Password`,
-> `Email`
-> FROM
-> `User`;
Empty set (0.00 sec)
mysql> SELECT `InsertUser`(NULL, 'pass', '[email protected]');
+------------------------------------------------+
| `InsertUser`(NULL, 'pass', '[email protected]') |
+------------------------------------------------+
| 1 |
+------------------------------------------------+
1 row in set (0.01 sec)
mysql> SELECT
-> `Id`,
-> `Username`,
-> `Password`,
-> `Email`
-> FROM
-> `User`;
+----+----------+------------------+-------+
| Id | Username | Password | Email |
+----+----------+------------------+-------+
| 1 | Nicki | [email protected] | pass |
+----+----------+------------------+-------+
1 row in set (0.00 sec)
mysql> SELECT `InsertUser`(NULL, 'pass', '[email protected]');
+------------------------------------------------+
| `InsertUser`(NULL, 'pass', '[email protected]') |
+------------------------------------------------+
| -2 |
+------------------------------------------------+
1 row in set (0.00 sec)
示例db-fiddle。