如何在mysql视图中传递动态参数

时间:2013-11-13 06:04:43

标签: mysql sql mysql-workbench mysql-select-db

我在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)

现在我想让“empId”和“emailType”动态化。我的意思是在选择时传递值。 什么需要改变代码? 提前谢谢

2 个答案:

答案 0 :(得分:10)

您可以将此解决方案与函数一起使用 -

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

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

使用示例:

SET @var = 1;
SELECT * FROM view1;

答案 1 :(得分:7)

只需创建不带参数的视图(即仅处理连接):

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

在查询时应用动态参数:

SELECT FNAME, LNAME, EMAIL
FROM   my_view
WHERE  eid = :empId AND emailtyp = :emailType