然后在同一个mysql语句中创建,设置然后使用变量

时间:2016-06-29 17:45:48

标签: mysql sql database variables

我正在尝试使用mysql语句中的变量并努力工作。

我现在有这个......

 SET @customer = 'UNKNOWN';
 SET @customer = (SELECT account FROM contacts WHERE emailaddy = 'myemailaddress' LIMIT 1);

 INSERT INTO cases
 (customer, details,severity,currentowner,created,createdautomatically)
 VALUES (@customer, 'This is a test case','SYS',now(),TRUE)

我得到'错误。必须定义参数'@customer'。

有人能指出我正确的方向吗?

编辑:在被告知我错过了声明之后,我已经添加了这个并且我仍然遇到同样的错误......

 DECLARE @customer VARCHAR(200);
 SET @customer = 'UNKNOWN';
 SET @customer = (SELECT account FROM contacts WHERE emailaddr = 'myemailaddress' LIMIT 1);

 INSERT INTO cases(customer, ....) VALUES (@customer, .....)

 Error. Parameter '@customer' must be defined..

另一个编辑......

似乎仍然无法正常工作:(

 DECLARE @customer VARCHAR(200);
 SET @customer := 'UNKNOWN';
 SET @customer := (SELECT account FROM contacts WHERE email = 'me');
 INSERT INTO cases (customer, ...) VALUES (@customer, '...')

 Error. Parameter '@customer' must be defined..

2 个答案:

答案 0 :(得分:1)

问题出在第1行

mysql> select "sss" into @customer;
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO funding(dONATUR) VALUES (@customer);
Query OK, 1 row affected (0.09 sec)

mysql> SELECT * FROM funding WHERE Donatur='sss';
+------+--------+---------+
| area | client | Donatur |
+------+--------+---------+
| NULL | NULL   | sss     |
+------+--------+---------+
1 row in set (0.00 sec)

答案 1 :(得分:0)

您可以尝试使用此查询:

SELECT @customer := COALESCE(`account`, 'UNKNOWN') FROM `contacts` WHERE `emailaddr` = 'myemailaddress' LIMIT 1;

INSERT INTO `cases` (customer, ...) VALUES (@customer, '...');