mysql stored procedures, views and triggers

view:

What is a view?

  Views are virtual tables that do not contain data themselves. Let's understand views better with an example:

  Assuming that in the above table, I need to query the product information provided by the specified supplier, then the SQL needs to be written as follows:

  

  This is just a simple two-table association, if we actually need a lot of SQL like this but more complex, then using a view would be a good choice, if I wrap the entire query into a virtual table called prodvend (view), then the same data can be easily retrieved.

      

  It can be seen that we can perform SELECT, filtering, etc. operations on views like ordinary tables, and views are just a facility for viewing data stored elsewhere. Views themselves contain data, and the data they return is from Retrieved from other tables, after making changes to these tables, the view will also be updated synchronously.

How to use the view:

  Views are created using the CREATE VIEW statement.

  The creation statement of the view prodevend in the above example is as follows:

CREATE VIEW prodvend AS
SELECT prod_name,prod_price
FROM products,vendors
where products.vend_id=vendors.vend_id;

  Views are dropped using the DROP VIEW statement.

Some rules for views:

  •   Like table names, view names must be unique
  •   An unlimited number of views can be created
  •   To create a view, a user with CREATE VIEW permission is required.
  •   Views can be used with tables, and you can write a SELECT statement that joins the table and the view.
  •   Views can be nested, which means you can create a view that uses another view.

  From the above example, it can be seen that the most important role of the view is to simplify complex connections .

View application:

  Simplify complex joins (most important);

  Use the view to reformat the retrieved data:

    As shown in the above table, assuming that we need to query the information of a certain commodity, we hope to get the format "commodity name (commodity price)". The SELECT statement should be written as follows:

SELECT CONCAT(prod_name,'(',prod_price,')')
AS productInfo
from products;

  The query result is as follows:

      

  If you often need results in this format, you can create a view and use it each time you need it.

copy code
CREATE  VIEW prodInfo AS 
SELECT prod_id,CONCAT(prod_name, ' ( ' ,prod_price, ' ) ' )
 AS productInfo
 from products;
 --If you want to query product information in this format, you can directly use 
SELECT  *  FROM prodInfo;
 --If only If you want to query a product, you can also 
SELECT  *  FROM prodInfo WHERE prod_id = 1 ;
copy code

Simplify calculated fields using views:

  In the same way, if you need to frequently use calculation calculations in queries, such as finding the product of the quantity and unit price in the order table, you can also create a view to save this operation, and you can directly query the view when you need it later. .

View update problem:

  Views are generally used to retrieve data, that is, together with SELECT, but views can also be updated. You can perform update (delete, update, insert) operations on views. If you add, delete, and modify views, you are actually correcting The base table has been added, deleted, and modified, but there are limitations at this time. If MySQL cannot correctly determine the base data that needs to be updated, the update is not allowed. For example, if the view definition has the following operations, the update is not allowed:

  Grouping, joins, subqueries, aggregate functions (MIN(), SUM()), etc. In fact, many views cannot be updated, but we need to know that the view itself is used for query. Generally, there is no need to update the view sex.


 

Stored procedure:  

What is a stored procedure?

  In practice, a complete requirement usually needs to operate multiple SQL statements to complete. To complete this requirement, multiple SQL statements for multiple tables are required. When writing code, each statement can be written separately and executed conditionally according to the result. Another statement. A disadvantage of this is that so much work must be done each time this processing is required. At this time, the encapsulation and reuse of requirements can be completed by creating stored procedures.  

  A stored procedure is simply a collection of one or more SQL statements that are saved for later use. Think of it as a batch file.

Use stored procedure:

  Create a stored procedure:

    Taking the table above as an example, suppose we now need to know the most expensive item in the item table, the cheapest item, and the average price of the item (although this doesn't make much sense). We could of course write a SELECT statement, or three Such statements are queried separately. Using stored procedures should be written like this:

copy code
CREATE  PROCEDURE productsPrice(
         --Accepts three parameters p1, p2, p3 parameters of type DECIMAL(8,2). 
        -- The OUT keyword is used to return to the caller 
    OUT p1 DECIMAL ( 8 , 2 ),
    OUT p2 DECIMAL(8,2),
    OUT p3 DECIMAL(8,2)
)
BEGIN
    SELECT MIN(prod_price) INTO p1 FROM products;
    SELECT Max(prod_price) INTO p2 FROM products;
    SELECT AVG(prod_price) INTO p3 FROM products;
END;
copy code

  Execute the stored procedure:

    In order to call the stored procedure created above, three variable names must be specified ( all MySQL variables must start with @ ), as follows:

       

  Note : When calling the stored procedure, this statement does not display data, it returns variables that can be displayed, so you can directly use the SELECT statement to query the variable name.

  You can see a stored procedure as a function. The function has a return value, and of course you can pass in parameters. Let's talk about a stored procedure with both parameters and return values. It can receive a product id and return the supplier of the product. city ​​of:

copy code
CREATE  PROCEDURE findCityById( --Incoming
            parameters , commodity id 
            IN prodID INT ,
           --returning the city 
          out vendCity VARCHAR ( 80 ))
 of the variable commodity supplier BEGIN SELECT v.vend_city 
     FROM products p,vendors v 
     WHERE p.vend_id = v. vend_id AND p.prod_id = prodID 
     INTO vendCity;
 END ;
    
copy code

  To use this stored procedure, you must pass two parameters to findCityById, the first parameter is the product id, and the second parameter is a variable name used to receive the supplier city, as follows:

  

  In fact, the stored procedures written above are just simple encapsulation of SQL statements. The use of stored procedures for such simple requirements will only make things more complicated. Only when the stored procedures contain complex business planning and intelligent processing, its power can be displayed. come out.

  Delete the stored procedure:

    Just use drop procedure+name.

The benefits (functions) of stored procedures:

  Simplify complex operations by encapsulating processing in easy-to-use units.

  Errors can be prevented by not requiring repeated establishment of a series of processing steps, because the more steps required to perform, the greater the possibility of errors, and the integrity and consistency of data can be guaranteed by using stored procedures.

  Simplifies the management of changes. If the table name, column name, or business logic changes, only the code in the stored procedure needs to be changed, and the people using the stored procedure don't even need to know about the changes.


trigger:

 What is a trigger?

  Whether it is a SQL statement or a stored procedure, it is executed when you need it, and a trigger, as the name suggests, is executed automatically when an event is triggered. For example, the following examples:

    Whenever a product is ordered, the quantity ordered is subtracted from the stock quantity.

    In practice, whenever you delete a row, you need to keep a copy of the deleted row in an archive table.

    When inserting a column with an English name, make sure the English is always uppercase, regardless of whether the name given in insert or update is uppercase or lowercase.

  The above examples have one thing in common is that they need to automatically process a certain logic when the table changes. In fact, this is a trigger. Triggers can only be executed when the table is changed, that is, only on delete, update, and insert statements.

  Create trigger:

   To create a trigger, you need to give 3 pieces of information:

      1. Unique trigger name (keep the trigger name unique under each database).

      2. The table associated with the trigger

      3. The corresponding activity of the trigger (delete, update or insert), and when to execute (before or after). 

   I am now going to create a simple trigger that displays a sentence "insert success!" when inserting a product record in the product table products;

    Note: In the trigger event of the trigger, you cannot only write select 'insert success', because the trigger does not allow to return a result set.

copy code
CREATE TRIGGER newProd AFTER INSERT ON products
for EACH ROW 
BEGIN
    SELECT 'insert success' INTO @info;
END;
copy code

  Note: Triggers are only supported for tables, views are not, and up to 6 triggers are supported in a table, which occurs before or after insert/delete/update.

  •   In an INSERT trigger, you can reference a virtual table called NEW to access the inserted row.

  •   In a DELETE trigger, you can reference a virtual table named OLD to access the row to be deleted.

  •   In the UPDATE trigger, there are both NEW and OLD, and the records before and after the update are saved.

  The following shows an example of using OLD to store the rows to be deleted into a backup table called backup:

copy code
CREATE TRIGGER deleteProd BEFORE DELETE ON products
for EACH ROW 
BEGIN
    INSERT INTO back_up(prod_id,vend_id,prod_name,prod_price)
    values(OLD.prod_id,OLD.vend_id,OLD.prod_name,OLD.prod_price);
END;
copy code

  Execute to delete a product with a primary key of 1, DELETE FROM products WHERE prod_id=1; you will find that there is an additional record in the back_up table, which is the product that was deleted.

 Delete trigger:

    Use drop trigger +name to delete.

 


 

  Reprinted to: http://www.cnblogs.com/fingerboy/p/5449796.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325792689&siteId=291194637