Mysql在select语句中设置局部变量,并仅使用一个查询返回相同的select输出

时间:2017-02-25 09:40:37

标签: mysql sql

我有客户表,我想返回客户信息并在本地变量中设置相同的内容。

declare customerId int;

declare customerName varchar(50);

select customerId=id, customerName=name, address, salary from customers where id=1;

然后我想使用这些局部变量customerId,customerName传递另一个函数。

即。 FUNC(客户ID,客户名称);

但是当我在mysql SP中选择这些变量时,我得到空值。有人能告诉我怎么做吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试此查询;

select @customerId := id, @customerName := name from customers 
where id = @customerId;

或者您可以在where condition中分配任何值。

注意,对于SET,可以使用=或:=作为赋值运算符。但是在其他语句中,赋值运算符必须是:=和not =因为=在非SET语句中被视为比较运算符。

答案 1 :(得分:0)

您可以执行此操作,如下所示:

SELECT @customerId := `id`, @customerName := `name` 
FROM customers
WHERE id = 'some value';

该查询的工作原理是列名称为idname

您可以对here进行类似的讨论。

<强>更新 根据问题的变化,答案会改变。

此部分将您想要的值分配给Local SQL Variables。

SELECT @customerId := `id`, @customerName := `name` 
FROM customers
WHERE id = 1;

此部分可用作SP的回复。

SELECT id, name, address, salary
FROM customers
WHERE id = 1;

希望这有帮助!