MySQL:在存储过程中将多个字段选择为多个变量


106

我可以在MySQL的同一选择查询中将多个列选择成多个变量吗?

例如:

DECLARE iId INT(20);
DECLARE dCreate DATETIME;

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

正确的语法是什么?

Answers:


220

您的语法不太正确:您需要按顺序在INTO之前列出字段,并在以下列出相应的目标变量:

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

6
+1。这是T-SQL语法更清晰的情况。将它们作为单独的列表会导致与DECLARE CURSOR和FETCH相同的维护问题(不是我,嗯,曾经使用过那些)。
harpo 2012年

同样适用于Pl / Sql。
Aniket Thakur

11

==========建议==========

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

请避免在存储过程中使用歧义变量。

范例:

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

您还可以通过引用表格使它们明确,例如:SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p WHERE pName = iName
maganap '16

2

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

SELECT Id, dateCreated FROM products INTO iId, dCreate

@KusalDissanayake这个问题被问到MySQL
ibai,
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.