sql >> Databasteknik >  >> RDS >> Mysql

Hur man skapar en lagrad procedur i MySQL med Knex raw

Detta borde hjälpa. Här skrev jag en modul förväntad av knex-migrera. Det borde inte vara några problem att anpassa sig efter ditt behov.

const mysql = require('mysql2');

const {
  database: {
    connection: {
      host, user, password, database, port
    }
  }
} = require('./settings.js');

exports.up = async () => {
  const script = `
    CREATE DEFINER=\`<YOUR_DB_USER>\`@\`%\` PROCEDURE \`fill_date_dimension\`(IN startdate DATE,IN stopdate DATE)
    BEGIN
        DECLARE currentdate DATE;
        SET currentdate = startdate;
        WHILE currentdate < stopdate DO
        INSERT INTO time_dimension VALUES (
                        YEAR(currentdate)*10000+MONTH(currentdate)*100 + DAY(currentdate),
                        currentdate,
                        YEAR(currentdate),
                        MONTH(currentdate),
                        DAY(currentdate),
                        QUARTER(currentdate),
                        WEEKOFYEAR(currentdate),
                        DATE_FORMAT(currentdate,'%W'),
                        DATE_FORMAT(currentdate,'%M'),
                        'f',
                        CASE DAYOFWEEK(currentdate) WHEN 1 THEN 't' WHEN 7 then 't' ELSE 'f' END,
                        NULL);
        SET currentdate = ADDDATE(currentdate,INTERVAL 1 DAY);
        END WHILE;
    END`

  const connection = mysql.createConnection({
    host,
    user,
    database,
    password,
    port
  });

  return new Promise(function (resolve, reject) {
    connection.query(
      script,
      function (err) {
        if (err) {
          return reject(err);
        }

        return resolve();
      }
    );
  });
};

exports.down = async knex => knex.raw('DROP PROCEDURE IF EXISTS fill_date_dimension');


  1. MySQL:datum före 1970

  2. Django - OperationalError:(1054, okänd kolumn 'xx' i 'fältlistan')

  3. 10 MySQL-databasintervjufrågor för nybörjare och intermediärer

  4. PDO lastInsertId fungerar inte på transaktioner?