0

I just reinstalled XAMPP using this installer: xampp-win32-1.8.3-2-VC11-installer. The issue below still exists. I have saved the routine, and have called it from the phpmyadmin sql console.

Environemnt: 5.6.14 - MySQL Community Server (GPL), Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.6

Breakdown is as follows: Trying to insert a record only if one does not previously exist. Once the record is inserted I request for that record to be returned, else return false. In the following stored procedure below I always get a false returning, even if a new record is inserted. It's like the ELSE statement is being ignored. Why is this occurring and how can it be corrected?

DROP PROCEDURE IF EXISTS `session_initiation`//

CREATE PROCEDURE `session_initiation`(
    IN _user_id     bigint(20),
    IN _device_id   bigint(20),
    IN _token       varchar(255)
)
BEGIN
    IF NOT EXISTS 
    (
        SELECT (1) from active_session where token = _token 
    )  
    THEN
        INSERT INTO active_session (user_id, device_id, token, datetime_create, datetime_expiry ) VALUES ( _user_id, _device_id, _token, NOW(), NOW() + INTERVAL 1 DAY );
        SELECT * from active_session where token = _token;
    ELSE
         SELECT FALSE;
    END IF;
END//

I would expect if the record does not exist, that the record would be inserted and then that same record would be returned. Instead I get the record inserted, and the following being returned:

FALSE
_____
  0

Appreciate anyone that can help correct my issue. I am running this directly from the SQL tab within phpmyadmin sql console.

Here are some calls to the procedure:

call session_initiation(1,1,'abc123')   //inserts and returns false = 0
call session_initiation(1,1,'123abc')   //inserts and returns false = 0
call session_initiation(1,1,'abc123')   //returns false = 0, does not reinsert the record.

As demo-ed by @wchiquito

The solution I provided is correct in SQL Fiddle. I made slight modifications to include an primary field, which is auto_incremented.

Here are the table details:

DROP TABLE IF EXISTS `active_session`;
CREATE TABLE IF NOT EXISTS `active_session` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) NOT NULL,
  `device_id` bigint(20) NOT NULL,
  `token` varchar(255) DEFAULT NULL,
  `datetime_create` datetime DEFAULT NULL,
  `datetime_expiry` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`session_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
4

1 回答 1

1

改变:

...
IF NOT EXISTS (SELECT (1) from active_session where token = _token) THEN
...

经过:

...
IF (SELECT (1) from active_session where token = _token) IS NOT NULL THEN
...

更新

创建测试后SQL Fiddle,您描述的问题我无法重现。您的代码按预期工作。存储过程似乎不是问题。

于 2014-03-12T18:33:19.040 回答