MySQL - 存储过程中的NULL值检查和动态SQL

时间:2010-06-17 06:25:54

标签: sql mysql stored-procedures dynamic null

1 个答案:

答案 0 :(得分:4)

遇到问题,应该是

DROP PROCEDURE IF EXISTS HaveSomeFun;
CREATE PROCEDURE HaveSomeFun(user_id CHAR(50),house_id CHAR(50),room_id CHAR(50),fun_text TEXT,video_url CHAR(100))
BEGIN
 DECLARE query_full TEXT;
 SET @fields_part = 'INSERT INTO fun(FunKey,UserKey,FunBody,LastModified';
 SET @values_part = CONCAT(') VALUES( NewBinKey(), KeyToBin(\"', user_id, '\"), \"', fun_text, '\", NOW() ');
 IF (house_id != '') THEN
  SET @fields_part = CONCAT(@fields_part, ', HouseKey');
  SET @values_part = CONCAT(@values_part, ', KeyToBin(\'', house_id, '\')');
 END IF;
 IF (room_id != '') THEN
  SET @fields_part = CONCAT(@fields_part, ', RoomKey');
  SET @values_part = CONCAT(@values_part, ', KeyToBin(\'', room_id, '\')');
 END IF;
 IF (video_url IS NOT NULL) THEN
  SET @fields_part = CONCAT(@fields_part, ', VideoURL');
  SET @values_part = CONCAT(@values_part, ', "', video_url, '"');
 END IF;
 SET query_full  = CONCAT(@fields_part, @values_part, ' );');
 SET @query_full = query_full;
 PREPARE STMT FROM @query_full;
 EXECUTE STMT;
 SELECT query_full;
END;