mysql> Create Procedure sp_Getnewtask(IN sdate datetime, IN edate datetime,IN sid int,IN tid int,OUT outmsg varchar(50))
-> begin
-> if not exists(
-> SELECT * FROM tbltask WHERE (startdate BETWEEN sdate AND edate)OR (enddate BETWEEN sdate AND edate) OR (sdate BETWEEN startdate AND enddate) OR (edate BETWEEN startdate AND enddate) OR Sid=Sid OR Tid=tid ) then
-> set outmsg = 'ADDED SUCESSFULLY';
-> else
-> set outmsg = 'RECORD ALREADY PRESENT';
-> end if;
-> end $$
mysql> select * from tbltask;
| tblid | startdate | enddate | Sid | Lid |
| 1 | 2011-05-20 00:00:00 | 2011-05-29 00:00:00 | NULL | NULL |
1 row in set (0.00 sec)
即使数据库中没有记录,它也显示为记录已存在,
如果我删除了sid,来自select查询的tid它正常工作, 请提出一些想法,以便正确运行输出
当我试图打电话给程序时, 它返回为,
mysql> call sp_Getnewtask('2011-05-20','2011-05-29',6,8,@outmsg);
-> select @outmsg;
-> $$
查询OK,0行受影响(0.00秒)
| @outmsg |
| RECORD ALREADY PRESENT |
1行(0.00秒)
但是我的实际结果应该是'添加成功'
答案 0 :(得分:0)
“ADDED SUCCESSFULLY”只应在select语句中没有选择记录时报告,但是在call sp_Getnewtask('2011-05-20','2011-05-29',6,8,@outmsg);
中给出输入变量你实际上在所有WHERE的OR条件中触发了6个条件中的4个。
编辑添加:
我运行了以下内容(包括结果)。我所做的就是更改变量的名称,这样你就不会得到一个始终为真的WHERE语句(SID=SID or TID=TID
将永远为真)。我还更改了SELECT
语句,以匹配您提供的表中的字段名称作为示例。
CREATE TABLE tbltask
(
tblid int,
startdate datetime,
enddate datetime,
sid int,
lid int
);
INSERT INTO `tbltask`(`tblid`, `startdate`, `enddate`) VALUES (1, '2011-05-20 00:00:00','2011-05-29 00:00:00');
DELIMITER //
CREATE Procedure sp_Getnewtask(IN sdate datetime, IN edate datetime,IN inSid int,IN inLid int,OUT outmsg varchar(50))
begin
if not exists
(
SELECT * FROM tbltask WHERE (startdate BETWEEN sdate AND edate)OR (enddate BETWEEN sdate AND edate) OR (sdate BETWEEN startdate AND enddate) OR (edate BETWEEN startdate AND enddate) OR Sid=inSid OR Lid=inLid
) then
set outmsg = 'ADDED SUCCESSFULLY';
else
set outmsg = 'RECORD ALREADY PRESENT';
end if;
end
//
call sp_Getnewtask('2011-05-20','2011-05-29',6,8,@outmsg);
select @outmsg;
RECORD ALREADY PRESENT
call sp_Getnewtask('2010-05-20','2010-05-29',6,8,@outmsg);
select @outmsg;
ADDED SUCCESSFULLY
目前看来,这似乎正在做它应该做的事情。如果任一日期范围应该相交,它将找到记录。如果它们不相交但是sid OR盖子匹配,那么它将找到记录。查找记录使其报告“记录已存在”