Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass dynamic parameters to a MySQL view

I have created the following view in MySQL:

CREATE VIEW MYVIEW AS (
SELECT A.FNAME
     , A.LNAME
     , B.EMAIL
FROM EMPLOYEE A, EMPEMAIL B
WHERE A.EID = :empId
  AND A.EID = B.EID
AND B.EMAILTYP = :emailType)

I have to make empId and emailType dynamic i.e. get the result for the desired values of empId and emailType at runtime.

What changes should be made in the code?

Thanks in advance.

like image 886
java baba Avatar asked Nov 13 '13 06:11

java baba


People also ask

Can we pass parameters to view in MySQL?

No can do. At least not directly. Use a procedure that populates a temporary table and reference the table in your code.

Can a view have input parameters?

No, in SQL Server, we cannot pass parameters to a view. And it can be considered as one main limitation of using a view in SQL Server.

Do MySQL views hold data?

Views are pure metadata. MySQL doesn't copy any data during the creating of a view, and it's also it is not deleted after a time. When you run a select on a view, mysql (or any other database) runs the query defined at creation time.

How does MySQL view work?

A view can contain all rows of a table or select rows from a table. A MySQL view can be created from one or many tables which depend on the written MySQL query to create a view. Structure data in a way that users or classes of users find natural or intuitive.


2 Answers

You can use this solution with a function -

CREATE FUNCTION func() RETURNS int(11)
  RETURN @var;

CREATE VIEW view1 AS
  SELECT * FROM table1 WHERE id = func();

Using example:

SET @var = 1;
SELECT * FROM view1;
like image 106
Devart Avatar answered Sep 19 '22 15:09

Devart


Just create the view without the parameters (i.e., to take care of the join only):

CREATE VIEW MYVIEW AS (
SELECT A.FNAME
     , A.LNAME
     , B.EMAIL
     , A.EID AS EID             -- added to be used in the WHERE
     , B.EMAILTYP AS EMAILTYP   -- added to be used in the WHERE
FROM EMPLOYEE A, EMPEMAIL B
WHERE A.EID = B.EID)

And apply the dynamic parameters when you query:

SELECT FNAME, LNAME, EMAIL
FROM   my_view
WHERE  eid = 'your_empId' AND emailtyp = 'your_emailType'

Note the WHERE shown above, it uses the two extra fields declared in the VIEW

like image 43
Mureinik Avatar answered Sep 18 '22 15:09

Mureinik