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

发布于 2024-08-25 18:30:59 字数 224 浏览 7 评论 0原文

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

例如:

DECLARE iId INT(20);
DECLARE dCreate DATETIME;

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

正确的语法是什么?

Can I SELECT multiple columns into multiple variables within the same select query in MySQL?

For example:

DECLARE iId INT(20);
DECLARE dCreate DATETIME;

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

What is the correct syntax for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无尽的现实 2024-09-01 18:30:59

您的语法不太正确:您需要按顺序列出 INTO 前面的字段,后面列出相应的目标变量:

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

Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:

SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName
海螺姑娘 2024-09-01 18:30:59

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

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

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

示例:

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

上面的示例将导致错误(空值错误)

下面给出的示例是正确的。我希望这是有道理的。

示例:

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

您还可以通过引用表格来使它们明确,例如:

[ Credit : maganap ]

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

==========Advise==========

@martin clayton Answer is correct, But this is an advise only.

Please avoid the use of ambiguous variable in the stored procedure.

Example :

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

The above example will cause an error (null value error)

Example give below is correct. I hope this make sense.

Example :

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

You can also make them unambiguous by referencing the table, like:

[ Credit : maganap ]

SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p 
WHERE pName = iName
橪书 2024-09-01 18:30:59

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

SELECT Id, dateCreated FROM products INTO iId, dCreate

Alternatively to Martin's answer, you could also add the INTO part at the end of the query to make the query more readable:

SELECT Id, dateCreated FROM products INTO iId, dCreate
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文