在mysql中存储过程变量

时间:2019-06-27 09:13:54

标签: mysql

我在过程中声明变量,并将这些值设置为另一个查询的结果。执行时,该变量为null。

版本:8.0.16

call putrequest('x',"jiraUPM","ASE-12345","inprogress","testcybsjira.com");

requestId和reqid不为null。但是它采用null值。

create procedure `putrequest`(in `employeeId` varchar(15),in `reqtype` 
 varchar(15),in `ticketId` varchar(15),in `status` varchar(15),in `details` 
 varchar(100))
 begin
  declare `rid` int;
  declare `reqType` int;
  select `requestId` into  `reqType` from `requesttype` where `request`=`reqtype`;
  select `reqId` into `rid` from `employee` where `empId`=`employeeId`;
  insert into `requests` values(rid,reqType,`ticketId`,NOW(),NOW(),`status`,`details`);
 end
  

执行SQL语句时出错。列'reqId'不能为空-连接:连接1:93ms

2 个答案:

答案 0 :(得分:0)

如果任何一个SELECT查询都找不到匹配的行,则对应的变量将为NULL,并且在尝试插入它时会出现错误。您需要先进行检查,然后再进行INSERT

但是不需要单独的SELECT查询和变量,请使用INSERT INTO ... SELECT ...

INSERT INTO requests
SELECT e.reqId, r.requestId, ticketId, NOW(), NOW(), status, details
FROM requesttype AS r
CROSS JOIN employee AS e
WHERE r.request = reqtype
AND e.empId = employeeId

如果找不到reqtypeemployeeId,则联接将不会返回任何行,因此将不会插入任何行。

答案 1 :(得分:0)

由于相同的变量名“ reqtype”(声明为过程参数)和“ reqType”(声明为过程变量)而导致问题

它将reqtype视为空值,并且不返回任何记录。

MySQL不区分大小写。给变量名时要小心。

DELIMITER $$
create procedure `putrequest`(in `employeeId` varchar(50),in `rtype` 
 varchar(50),in `ticketId` varchar(15),in `status` varchar(15),in `details` 
 varchar(100))
begin
  declare `rid` int;
  declare `reqType` int;
  select `reqId` into `rid` from `employee` where `empId`=`employeeId`;
  select `requestId` into  `reqType` from requesttype where `request`=`rtype`;
  insert into `requests` values(rid,reqType,`ticketId`,NOW(),NOW(),`status`,`details`);
end$$
DELIMITER ;

DEMO