MySQL:在存储过程中select多个字段为多个variables

我可以在MySQL的同一个select查询中select多个列到多个variables吗?

例如:

DECLARE iId INT(20); DECLARE dCreate DATETIME; SELECT Id INTO iId, dateCreated INTO dCreate FROM products WHERE pName=iName; 

这是什么正确的语法?

你的语法不是很正确:你需要在INTO之前按顺序列出这些字段,以及相应的目标variables:

 SELECT Id, dateCreated INTO iId, dCreate FROM products WHERE pName = iName 

========== ==========build议

@martin clayton答案是正确的,但这只是一个build议。

请避免在存储过程中使用不明确的variables。

例如:

 SELECT Id, dateCreated INTO id, datecreated FROM products WHERE pName = iName 

上面的例子会导致一个错误(空值错误)

下面的例子是正确的。 我希望这是有道理的。

例如:

 SELECT Id, dateCreated INTO val_id, val_datecreated FROM products WHERE pName = iName 

您也可以通过引用表格使它们毫不含糊,如:

[信用: maganap ]

 SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p WHERE pName = iName 

除了Martin的回答,您还可以在查询结尾处添加INTO部分以使查询更具可读性:

 SELECT Id, dateCreated FROM products INTO iId, dCreate