@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。
你已經有一個叫Nicki的用戶嗎?您正在將「Nicki」硬編碼到插入中,而不是像我期望的那樣使用@Username。如果你已經有一個用戶名Nicki,並且該字段是唯一/主鍵等,它將失敗。如果不是這種情況,請自己運行兩個'SELECT'語句('SELECT * FROM用戶WHERE用戶名= @用戶名'和電子郵件地址相同),並指定用戶名和電子郵件地址。檢查他們是否返回值 –
您返回的值是什麼? –
嘿好吧謝謝,但我沒有任何價值在我的Tabel。她是我的結構:https://pastebin.com/kZ0zaxD4 – N1ck1