difference between the use of functions, views, triggers and stored procedures in sql server and mysql

1

Well I hope to do this well, it's the first time I ask on this site.

What are triggers, functions, views and stored procedures? The truth is I'm starting in this database and I have many doubts in the use of functions, views, trigger and PA from the function of each of them and their differences since some are very similar in structure and would like to know when should use each one of them, in which problems is necessary for example better a trigger than a PA or a view that a trigger and when not. When to use each of them in a problem?

Well I hope it is not a question of much discomfort or very silly, in advance I thank you for answering me.

    
asked by Jack 24.03.2018 в 00:25
source

1 answer

1

I will mention for example a PA (Stored Procedure) , it will keep inside you a sequence of one or several SQL statements, from which you will later be able to obtain utility and it will suffice that you only invoke the PA for its name, as I show you in the following example:

Explanatory note: The examples I will show you are for MySQL but I assume that the logic and degree of functionality should be very similar to SQL Server

DELIMITER $$
CREATE PROCEDURE datos()
BEGIN
   SELECT usuarios.*, categorias.* FROM usuarios
JOIN categorias
ON  usuarios.id_categoria = categorias.id
WHERE usuarios.id_categoria = 1;
END $$

As you can notice in the following line I invoke said PA only with call and the name of it.

call datos();

On the other hand the views or views for example are stored on server then that helps the workload, a view is a representation of the data but does not imply direct access to them and by last in a PA you can pass parameters that will be used within your SQL query, but in the views not because they are only a static representation of the data

// EXAMPLE

--Aquí creo la vista y le asigno un nombre y con AS le indico la lógica SQL que tednrá que ejecutar
CREATE VIEW 
users_posts AS 
SELECT users.id,name, status 
FROM users 
JOIN posts 
ON users.id = posts.id_user;

--Para poder hacer uso de la vista la meto en una instrucción SQL regular y al final paso el nombre de dicha vista
SELECT * FROM users_posts;

The triggers are used to store queries and determine when they will be executed, the syntax is:

CREATE TRIGGER nombre_trigger
BEFORE INSERT
   ON nombre_tabla FOR EACH ROW
BEGIN
   --El código que será ejecutado por el trigger va aquí es decir las sentencias SQL
END;
    
answered by 24.03.2018 в 00:51