MySQL 5.7 create VIEW or FUNCTION or PROCEDURE

1.视图
a.
CREATE
    ALGORITHM = UNDEFINED
    DEFINER = `root`@`localhost`
    SQL SECURITY INVOKER
VIEW `sakila`.`actor_info` AS
    SELECT
        `a`.`actor_id` AS `actor_id`,
        `a`.`first_name` AS `first_name`,
        `a`.`last_name` AS `last_name`,
        GROUP_CONCAT(DISTINCT CONCAT(`c`.`name`,
                    ‘: ‘,
                    (SELECT
                            GROUP_CONCAT(`f`.`title`
                                    ORDER BY `f`.`title` ASC
                                    SEPARATOR ‘, ‘)
                        FROM
                            ((`sakila`.`film` `f`
                            JOIN `sakila`.`film_category` `fc` ON ((`f`.`film_id` = `fc`.`film_id`)))
                            JOIN `sakila`.`film_actor` `fa` ON ((`f`.`film_id` = `fa`.`film_id`)))
                        WHERE
                            ((`fc`.`category_id` = `c`.`category_id`)
                                AND (`fa`.`actor_id` = `a`.`actor_id`))))
            ORDER BY `c`.`name` ASC
            SEPARATOR ‘; ‘) AS `film_info`
    FROM
        (((`sakila`.`actor` `a`
        LEFT JOIN `sakila`.`film_actor` `fa` ON ((`a`.`actor_id` = `fa`.`actor_id`)))
        LEFT JOIN `sakila`.`film_category` `fc` ON ((`fa`.`film_id` = `fc`.`film_id`)))
        LEFT JOIN `sakila`.`category` `c` ON ((`fc`.`category_id` = `c`.`category_id`)))
GROUP BY `a`.`actor_id` , `a`.`first_name` , `a`.`last_name`

b.

CREATE
    ALGORITHM = UNDEFINED
    DEFINER = `root`@`localhost`
    SQL SECURITY DEFINER
VIEW `sakila`.`staff_list` AS
    SELECT
        `s`.`staff_id` AS `ID`,
        CONCAT(`s`.`first_name`,
                _UTF8‘ ‘,
                `s`.`last_name`) AS `name`,
        `a`.`address` AS `address`,
        `a`.`postal_code` AS `zip code`,
        `a`.`phone` AS `phone`,
        `sakila`.`city`.`city` AS `city`,
        `sakila`.`country`.`country` AS `country`,
        `s`.`store_id` AS `SID`
    FROM
        (((`sakila`.`staff` `s`
        JOIN `sakila`.`address` `a` ON ((`s`.`address_id` = `a`.`address_id`)))
        JOIN `sakila`.`city` ON ((`a`.`city_id` = `sakila`.`city`.`city_id`)))
        JOIN `sakila`.`country` ON ((`sakila`.`city`.`country_id` = `sakila`.`country`.`country_id`)))

2.存储过程
a.
CREATE DEFINER=`root`@`localhost` PROCEDURE `film_in_stock`(IN p_film_id INT, IN p_store_id INT, OUT p_film_count INT)
    READS SQL DATA
BEGIN
     SELECT inventory_id
     FROM inventory
     WHERE film_id = p_film_id
     AND store_id = p_store_id
     AND inventory_in_stock(inventory_id);

     SELECT FOUND_ROWS() INTO p_film_count;
END

b.
CREATE DEFINER=`root`@`localhost` PROCEDURE `rewards_report`(
    IN min_monthly_purchases TINYINT UNSIGNED
    , IN min_dollar_amount_purchased DECIMAL(10,2) UNSIGNED
    , OUT count_rewardees INT
)
    READS SQL DATA
    COMMENT ‘Provides a customizable report on best customers‘
proc: BEGIN

    DECLARE last_month_start DATE;
    DECLARE last_month_end DATE;

    /* Some sanity checks... */
    IF min_monthly_purchases = 0 THEN
        SELECT ‘Minimum monthly purchases parameter must be > 0‘;
        LEAVE proc;
    END IF;
    IF min_dollar_amount_purchased = 0.00 THEN
        SELECT ‘Minimum monthly dollar amount purchased parameter must be > $0.00‘;
        LEAVE proc;
    END IF;

    /* Determine start and end time periods */
    SET last_month_start = DATE_SUB(CURRENT_DATE(), INTERVAL 1 MONTH);
    SET last_month_start = STR_TO_DATE(CONCAT(YEAR(last_month_start),‘-‘,MONTH(last_month_start),‘-01‘),‘%Y-%m-%d‘);
    SET last_month_end = LAST_DAY(last_month_start);

    /*
        Create a temporary storage area for
        Customer IDs.
    */
    CREATE TEMPORARY TABLE tmpCustomer (customer_id SMALLINT UNSIGNED NOT NULL PRIMARY KEY);

    /*
        Find all customers meeting the
        monthly purchase requirements
    */
    INSERT INTO tmpCustomer (customer_id)
    SELECT p.customer_id
    FROM payment AS p
    WHERE DATE(p.payment_date) BETWEEN last_month_start AND last_month_end
    GROUP BY customer_id
    HAVING SUM(p.amount) > min_dollar_amount_purchased
    AND COUNT(customer_id) > min_monthly_purchases;

    /* Populate OUT parameter with count of found customers */
    SELECT COUNT(*) FROM tmpCustomer INTO count_rewardees;

    /*
        Output ALL customer information of matching rewardees.
        Customize output as needed.
    */
    SELECT c.*
    FROM tmpCustomer AS t
    INNER JOIN customer AS c ON t.customer_id = c.customer_id;

    /* Clean up */
    DROP TABLE tmpCustomer;
END

3.函数
a.
CREATE DEFINER=`root`@`localhost` FUNCTION `get_customer_balance`(p_customer_id INT, p_effective_date DATETIME) RETURNS decimal(5,2)
    READS SQL DATA
    DETERMINISTIC
BEGIN

       #OK, WE NEED TO CALCULATE THE CURRENT BALANCE GIVEN A CUSTOMER_ID AND A DATE
       #THAT WE WANT THE BALANCE TO BE EFFECTIVE FOR. THE BALANCE IS:
       #   1) RENTAL FEES FOR ALL PREVIOUS RENTALS
       #   2) ONE DOLLAR FOR EVERY DAY THE PREVIOUS RENTALS ARE OVERDUE
       #   3) IF A FILM IS MORE THAN RENTAL_DURATION * 2 OVERDUE, CHARGE THE REPLACEMENT_COST
       #   4) SUBTRACT ALL PAYMENTS MADE BEFORE THE DATE SPECIFIED

  DECLARE v_rentfees DECIMAL(5,2); #FEES PAID TO RENT THE VIDEOS INITIALLY
  DECLARE v_overfees INTEGER;      #LATE FEES FOR PRIOR RENTALS
  DECLARE v_payments DECIMAL(5,2); #SUM OF PAYMENTS MADE PREVIOUSLY

  SELECT IFNULL(SUM(film.rental_rate),0) INTO v_rentfees
    FROM film, inventory, rental
    WHERE film.film_id = inventory.film_id
      AND inventory.inventory_id = rental.inventory_id
      AND rental.rental_date <= p_effective_date
      AND rental.customer_id = p_customer_id;

  SELECT IFNULL(SUM(IF((TO_DAYS(rental.return_date) - TO_DAYS(rental.rental_date)) > film.rental_duration,
        ((TO_DAYS(rental.return_date) - TO_DAYS(rental.rental_date)) - film.rental_duration),0)),0) INTO v_overfees
    FROM rental, inventory, film
    WHERE film.film_id = inventory.film_id
      AND inventory.inventory_id = rental.inventory_id
      AND rental.rental_date <= p_effective_date
      AND rental.customer_id = p_customer_id;

  SELECT IFNULL(SUM(payment.amount),0) INTO v_payments
    FROM payment

    WHERE payment.payment_date <= p_effective_date
    AND payment.customer_id = p_customer_id;

  RETURN v_rentfees + v_overfees - v_payments;
END

b.
CREATE DEFINER=`root`@`localhost` FUNCTION `inventory_in_stock`(p_inventory_id INT) RETURNS tinyint(1)
    READS SQL DATA
BEGIN
    DECLARE v_rentals INT;
    DECLARE v_out     INT;

    #AN ITEM IS IN-STOCK IF THERE ARE EITHER NO ROWS IN THE rental TABLE
    #FOR THE ITEM OR ALL ROWS HAVE return_date POPULATED

    SELECT COUNT(*) INTO v_rentals
    FROM rental
    WHERE inventory_id = p_inventory_id;

    IF v_rentals = 0 THEN
      RETURN TRUE;
    END IF;

    SELECT COUNT(rental_id) INTO v_out
    FROM inventory LEFT JOIN rental USING(inventory_id)
    WHERE inventory.inventory_id = p_inventory_id
    AND rental.return_date IS NULL;

    IF v_out > 0 THEN
      RETURN FALSE;
    ELSE
      RETURN TRUE;
    END IF;
END

  

时间: 2024-11-08 03:02:18

MySQL 5.7 create VIEW or FUNCTION or PROCEDURE的相关文章

MySQL 自定义函数CREATE FUNCTION实例

分享一个MySQL 自定义函数CREATE FUNCTION的实例.mysql> delimiter $$mysql> CREATE FUNCTION myFunction-> (in_string VARCHAR(255),-> in_find_str VARCHAR(20),-> in_repl_str VARCHAR(20))->-> RETURNS VARCHAR(255)-> BEGIN-> DECLARE l_new_string VARC

Mysql数据库理论基础之六--VIEW视图

一.简介 由MySQL AB公司开发,是最流行的开放源码SQL数据库管理系统,主要特点: 1.是一种数据库管理系统 2.是一种关联数据库管理系统 3.是一种开放源码软件,且有大量可用的共享MySQL软件 4.MySQL数据库服务器具有快速.可靠和易于使用的特点 5.MySQL服务器工作在客户端/服务器模式下,或嵌入式系统中 InnoDB存储引擎将InnoDB表保存在一个表空间内,该表空间可由数个文件创建.这样,表的大小就能超过单独文件的最大容量.表空间可包括原始磁盘分区,从而使得很大的表成为可能

SQL基础语法—create view语句

1 create view语句介绍 create view语句是将某个查询数据的定义保留下来,以便随时调用,这就是所谓的视图.视图本身不存储查询结果,只是一个定义. Syntax: CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER }] [SQL SECURITY { DEFINER | INVOKER }] VIEW view_name [(col

mysql can&#39;t create threads in threadpool

最近,我们在券商端的mysql运行一段时间后,发生mysql can't create threads in threadpool,如下所示: 据官网一个报告显示,目测是一个bug,内存紧张导致,那天也没及时看,明后天再观察看看,现在是没有问题了. mysql can't create threads in threadpool

linux之SQL语句简明教程---CREATE VIEW

视观表 (View) 可以被当作是虚拟表格.它跟表格的不同是,表格中有实际储存资料,而视观表是建立在表格之上的一个架构,它本身并不实际储存资料. 建立一个视观表的语法如下: CREATE VIEW "VIEW_NAME" AS "SQL 语句"; "SQL 语句" 可以是任何一个我们在这个教材中有提到的 SQL. 来看一个例子.假设我们有以下的表格: Customer 表格 栏位名称 资料种类 First_Name char(50) Last_N

create view in view

CREATE VIEW view_region2role AS ( SELECT region_set_id, region_set_name, GROUP_CONCAT(id) gc_id, GROUP_CONCAT(name) gc_name FROM view_region_role GROUP BY region_set_id )

SQL Server 视图的创建- (create view必须是批处理中仅有的语句)

当我们SQL Server在创建视图时 ,会出现"create view 必须是批处理中仅有的语句"这个语法错误提示 ,实际上这本身没什么错! 因为create view 必须是批处理中的第一条语句.也就是说,你可能在这段代码之前还有其他的语句是同时处理的,为此,你可以在这段代码的前一行加上GO,在这段代码结束后一行加上GO就可以了..或者你把这段代码单独执行就不会出错了.    

CREATE OR REPLACE FUNCTION

CREATE OR REPLACE FUNCTION SF_Taishou_Ksai_Date(v_receiptNum IN CHAR,                                                v_his        IN CHAR)  RETURN VARCHAR2 DETERMINISTIC IS  RESULT              VARCHAR2(50);  v_result_t          VARCHAR2(50);  v_tmp_

How to create DB2 user function easily by DB Query Analyzer 6.03

How to create DB2user function easily by DB Query Analyzer 6.03 Ma Genfeng (Guangdong Unitoll Servicesincorporated, Guangzhou510300) Abstract  The latest version of DB QueryAnalyzer is 6.03 In DB Query Analyzer 6.03, without changing any Windows OS s