2016-11-17 45 views
1

我写MySQL中的过程将通过DESC一个字符串值,从而,如何通过声明

IN `para` varchar(4) 
BEGIN 
    #Routine body goes here... 

if (para = 'asc') THEN 

SELECT officeCode, city, country 
from offices 
ORDER BY country ; 

ELSE 

SELECT officeCode, city, country 
from offices 
ORDER BY country DESC; 


END if; 
END 

该代码是好的,但我不知道是否有任何其他方法,使短,像这样的(第为参数时调用程序):

BEGIN 
SELECT officeCode, city, country 
from offices 
ORDER BY country *para* ; 

END 
--------but this is not work------- 

回答

0

你可以很容易地动态地根据para使用自己选择的任何脚本语言生成查询的文本,如果在你的解决方案工作。

0

这里有一个窍门,你可以用CASE表达式中使用:

SELECT officeCode, 
     city, 
     country 
FROM offices 
ORDER BY CASE WHEN para = 'asc' THEN Country ELSE '1' END ASC, 
     CASE WHEN para != 'asc' THEN Country ELSE '1' END DESC; 
0

你有两个选择。一种是与order by拨弄:

SELECT officeCode, city, country 
FROM offices 
ORDER BY (CASE WHEN para = 'asc' THEN country END), 
     country DESC; -- you could use a `case` here but it is not necessary 

或者,你可以使用一个事先准备好的声明:

set @sql = ' 
SELECT officeCode, city, country 
FROM offices 
ORDER BY para [dir]'; 

set @sql = replace(@sql, '[dir]', (case when para = 'asc' then 'asc' else 'desc' end)); 

prepare q from @sql; 
execute q; 

动态SQL的好处是,你有一个希望查询将使用索引。