mysql 存储过程 动态sql例子

proc:BEGIN
DECLARE _count INT DEFAULt 0;
DECLARE _eventID INT DEFAULT 0;
DECLARE _status INT DEFAULT 0;
DECLARE _startTime VARCHAR(19) DEFAULT '';
DECLARE _endTime VARCHAR(19) DEFAULT '';
DECLARE _tblAccessLog VARCHAR(30) DEFAULT '';#插入日志的表,一个活动一张表 #将局部变量转换成会话变量
#动态sql语言只接受会话变量
SET @iFieldID=iFieldID;
SET @sUID=sUID;
SET @sIP=sIP;
SET @sCreateTime=sCreateTime; #判断字段状态
SELECT event_id,`status` INTO _eventID,_status
FROM portal_tongji_event_field
WHERE id=iFieldID; IF _eventID=0 THEN
SELECT -10001 AS retCode,'该字段不存在' AS retMsg;
LEAVE proc;
END IF;
IF _status=2 THEN
SELECT -10002 AS retCode,'该字段已禁用' AS retMsg;
LEAVE proc;
END IF; #判断活动状态
SELECT COUNT(*),`status`,start_time,end_time INTO _count,_status,_startTime,_endTime
FROM portal_tongji_event_info
WHERE id=_eventID; IF _count=0 THEN
SELECT -10003 AS retCode,'该活动不存在' AS retMsg;
LEAVE proc;
END IF;
IF _status=2 THEN
SELECT -10004 AS retCode,'该活动已禁用' AS retMsg;
LEAVE proc;
END IF;
IF _startTime>CURDATE() THEN
SELECT -10005 AS retCode,'活动未开始' AS retMsg;
LEAVE proc;
END IF;
IF _endTime<CURDATE() THEN
SELECT -10006 AS retCode,'活动已结束' AS retMsg;
LEAVE proc;
END IF; #判断日志表是否存在
SET _tblAccessLog=CONCAT('portal_tongji_access_log_',_eventID); SELECT COUNT(*) INTO _count
FROM information_schema.TABLES
WHERE table_name =_tblAccessLog; IF _count=0 THEN
SET @strSql=CONCAT('CREATE TABLE ',_tblAccessLog,' (`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,`field_id` smallint(5) unsigned NOT NULL COMMENT \'统计字段ID\',`uid` varchar(24) NOT NULL COMMENT \'用户账号\',`ip` varchar(15) NOT NULL COMMENT \'用户IP\',`create_time` datetime NOT NULL COMMENT \'创建时间\',PRIMARY KEY (`id`),KEY `field_id` (`field_id`)) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=gbk;');
PREPARE stmt FROM @strSql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF; #插入日志
SET @strSql=CONCAT('INSERT ',_tblAccessLog,' VALUES(NULL,?,?,?,?);');
PREPARE stmt FROM @strSql;
EXECUTE stmt USING @iFieldID,@sUID,@sIP,@sCreateTime;
DEALLOCATE PREPARE stmt; IF last_insert_id()>0 THEN
SELECT 10000 AS retCode,'操作成功' AS retMsg;
ELSE
SELECT -10005 AS retCode,'插入失败' AS retMsg;
END IF;
END

#输入参数:  IN iFieldID tinyint(3),IN sUID varchar(24),IN sIP varchar(15),IN sCreateTime varchar(19)

上一篇:MySQL 存储过程常用SQL语句收集


下一篇:module ‘skimage‘ has no attribute ‘transform‘