如何在函数内部使用动态查询

时间:2014-02-12 15:12:37

标签: mysql sql

我正在尝试创建一个函数GETUSERPROP(prop,filter_prop,filter_value),它按属性和值选择数据库中的一个项

SET @_GET_PROP      = "name";
SET @_FILTER_PROP   = "id";
SET @_FILTER_VALUE  = "15";

SET @q = CONCAT(
    ' SELECT ', 
    @_GET_PROP,
    ' FROM MYVIEW '
    ' WHERE 1 ',    
    ' AND (`', @_FILTER_PROP, '` = "', @_FILTER_VALUE, '") '
);
PREPARE stmt FROM @q;
EXECUTE stmt;

查询外部函数运行正常,但是当我尝试将其置于函数内时,我收到错误

mysql dynamic sql is not allowed in stored function or trigger

我需要这个函数在其他查询中使用,如下所示:

SELECT 
    GETUSERPROP("name", "id", "15") AS name,
    GETUSERPROP("age",  "id", "15") AS age

1 个答案:

答案 0 :(得分:1)

从错误消息中可以明显看出我们无法在函数中使用动态sql。动态sql只能在程序中使用。所以你必须考虑另类。如果组合的数量不是太多,那么您可以为每个可能的组合使用IF语句。

IF @_GET_PROP = 'name' AND @_FILTER_PROP = 'ID' THEN
  SELECT name from MYVIEW where id = @_FILTER_VALUE;
ELSE IF @_GET_PROP = 'Agen' AND @_FILTER_PROP = 'ID' THEN
  SELECT name from MYVIEW where id = @_FILTER_VALUE;

................ ...............

依旧......

或类似的东西

SELECT CASE @_GET_PROP WHen 'name' then name when 'id' then ID when 'Age' then Age END from MYVIEW where 
 ((@_FILTER_PROP = 'ID' AND id = @_FILTER_VALUE)
 or (@_FILTER_PROP = 'name' AND name = @_FILTER_VALUE)
or (@_FILTER_PROP = 'age' AND age = @_FILTER_VALUE)
) ;