一个导数据的存储过程

DELIMITER $$

USE `gongwuyuan_0630`$$

DROP PROCEDURE IF EXISTS `cp_data`$$

CREATE DEFINER = `space` @`172.21.%` PROCEDURE `cp_data` (IN tb_name VARCHAR (100)) 
BEGIN
  DECLARE v_result_tb_name VARCHAR (100) ;
  DECLARE v_note_tb_name VARCHAR (100) ;
  DECLARE v_mark_tb_name VARCHAR (100) ;
  DECLARE v_ol_question VARCHAR (100) ;
  DECLARE v_old_db VARCHAR (100) ;
  DECLARE v_new_db VARCHAR (100) ;
  DECLARE v_mark_id INT ;
  DECLARE v_tid INT ;
 
  #修改数据库名,需要根据生产环境修改数据名
  SET v_old_db = "gongwuyuan_0630" ;
  SET v_new_db = "chapter_591up" ;
 
  SET v_ol_question = CONCAT(v_old_db, ".ol_question") ;
  SET v_note_tb_name = CONCAT(v_new_db,'.common_questionnote') ;
  SELECT SUBSTRING(tb_name,LENGTH('new_answerresult_') + 1) INTO v_tid ;
 
  SET v_result_tb_name = CONCAT(v_new_db, '.answerresult_', v_tid) ;
  SELECT MOD(v_tid, 20) INTO v_mark_id ;
  SET v_mark_tb_name = CONCAT(v_new_db,'.markedquestion_',v_mark_id);
 
  SET tb_name = CONCAT(v_old_db, ".", tb_name) ;
  #1. 插入作答记录表
  SET @SQL_CONTEXT = CONCAT(
    "INSERT IGNORE INTO ",v_result_tb_name,
    " (`CourseId`,`UserId`,`QuestionId`,`TotalRightCount`,`TotalWrongCount`
,`TotalCount`,`TotalCostTime`,`IsLastRight`,`LastResult`,`LastCostTime`,
`LastTime`
) SELECT 
n.SUBJECT,
  n.UserId,
q.Id,
  n.CorrectCount,
   n.ErrorCount,
   n.TotalCount,
   n.TotalCostTime,
   n.LastIsCorrect,
   REPLACE(
    REPLACE(
      REPLACE(
        REPLACE(
          LastAnswerXML,
          ']]></i></a><a><i><![CDATA[',
          '",
    "'
        ),
        '<as><a><i><![CDATA[',
        '[""'
      ),
      ']]></i></a></as>',
      '""]'
    ),
    '<as></as>',
    ''
  ) json,
  #n.LastAnswerXML,
  if(n.LastCostTime>32767,32767,n.LastCostTime)LastCostTime,
   n.LastAnswerTime
FROM ",tb_name," n INNER JOIN ",v_ol_question,
    " q USING(questionid) WHERE n.SUBJECT = 10") ;
  PREPARE smtp FROM @SQL_CONTEXT ;
  EXECUTE smtp ;
  DEALLOCATE PREPARE smtp ;
  #2.插入笔记
  SET @SQL_CONTEXT = CONCAT(
    "INSERT IGNORE INTO ",v_note_tb_name,"(`UserId`,`QuestionId`,`Content`,`IsPublic`,`IsAudited`,`UpdateTime`,`DigCount`)
SELECT 
  n.UserId,
q.Id,
n.Reviews,
n.IsPublic, 
 1,
 n.LastAnswerTime,
 0
FROM ",tb_name," n INNER JOIN ",v_ol_question,
    " q USING(questionid)
WHERE n.SUBJECT = 10 AND Reviews>'' AND Reviews<>'为什么做错了?是因为....'"
  ) ;
  PREPARE smtp FROM @SQL_CONTEXT ;
  EXECUTE smtp ;
  DEALLOCATE PREPARE smtp ;
  #3. 导入错题
  SET @SQL_CONTEXT = CONCAT(
    "INSERT IGNORE INTO ",v_mark_tb_name,"(
  `UserId`,
  `QuestionId`,
  `TypeId`,
  `RootCatalogId`,
  `CreateTime`,
  `CourseId`
) 
SELECT 
  n.UserId,
  q.Id,
  n.AnswerResultCategory,
  n.RootCatalogId,
  n.LastAnswerTime,
  n.SUBJECT 
FROM ",tb_name," n   INNER JOIN ",v_ol_question," q USING (questionid) 
WHERE n.SUBJECT = 10 
  AND AnswerResultCategory IN (2, 3, 6)"  );
  PREPARE smtp FROM @SQL_CONTEXT ;
  #select @SQL_CONTEXT;
  EXECUTE smtp ;
  DEALLOCATE PREPARE smtp ;
END $$

DELIMITER ;

你可能感兴趣的:(sql,xml)