3

在 MYSQL 存储过程中,我需要选择两个表列,并将列选择到变量中,以便在该过程中进一步使用。

下面是存储过程的简化版本。

DECLARE pUSR_ID BIGINT;
DECLARE pPRJ_ID BIGINT;
DECLARE pUSR_LAN_ID BIGINT;

SELECT USR_ID, USR_Login, USR_Password, USR_Archived, USR_Deleted, 
  USR_ID, USR_PRJ_ID, USR_LAN_ID INTO pUSR_ID, pPRJ_ID, pUSR_LAN_ID
FROM tblUsers
WHERE USR_Login = 'foobar';

当我执行上述存储过程时,我收到以下错误消息,这是有道理的。

Error Code: 1222. The used SELECT statements have a different number of columns

所以,我把变量放在第一位,其他列放在变量之后。

SELECT USR_ID, USR_PRJ_ID, USR_LAN_ID INTO pUSR_ID, pPRJ_ID, pUSR_LAN_ID,
  USR_ID, USR_Login, USR_Password, USR_FullName, USR_IsProjectAdmin, USR_Archived,
  USR_Deleted
执行此返回:Error 1327: Undeclared variable: USR_ID。我明白为什么我会收到错误。

我不明白的是如何在同一个语句中选择表列并将某些列选择到变量中?

4

1 回答 1

3
/*
DECLARE pUSR_ID BIGINT;
DECLARE pPRJ_ID BIGINT;
DECLARE pUSR_LAN_ID BIGINT;
*/ /*no need to declare*/


SELECT 
@pUSR_ID:=USR_ID, 
USR_Login, 
USR_Password, 
USR_Archived, 
USR_Deleted, 
USR_ID, 
@pPRJ_ID:=USR_PRJ_ID, 
@pUSR_LAN_ID:=USR_LAN_ID 
FROM tblUsers
WHERE USR_Login = 'foobar';
于 2012-12-17T14:59:13.880 回答