我试图在NamedParameterJdbcTemplate中使用查询,为Postgresql编写if条件的查询。
我将2个参数传递给query,store和tot_store。我尝试了以下查询,但它不起作用。有什么建议吗?
IF (:store=1)
BEGIN
SELECT * FROM store_pricing WHERE store = :store and tot_store = :tot_store ORDER BY store asc;
END
ELSE IF (:store = 2)
BEGIN
SELECT * FROM store_pricing WHERE store = :store and tot_store = :tot_store ORDER BY store asc;
END
ELSE
BEGIN
SELECT * FROM store_pricing WHERE store = :store and tot_store = :tot_store ORDER BY store desc;
END
错误说
syntax error at or near "IF"
提前谢谢
答案 0 :(得分:0)
PostgreSQL doesn't accept IF
as a top level statement. It's not SQL-standard either.
Use CASE ... WHEN ...
IF
is permitted in PL/PgSQL
code blocks, though; see DO
and CREATE FUNCTION
.
In this case I'd write a single SQL statement and
ORDER BY
CASE WHEN store IN (1,2) THEN -store
ELSE store
END DESC
(untested)
答案 1 :(得分:0)
如果您使用的是Mysql,则代码中的IF语句不正确。 正确的IF语法:
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
你需要摆脱括号,然后把它放在条件之后。
例如,您可以编写这样的存储过程:
DELIMITER //
CREATE FUNCTION SimpleCompare(n INT, m INT)
RETURNS VARCHAR(20)
BEGIN
DECLARE s VARCHAR(20);
IF n > m THEN SET s = '>';
ELSEIF n = m THEN SET s = '=';
ELSE SET s = '<';
END IF;
SET s = CONCAT(n, ' ', s, ' ', m);
RETURN s;
END //
DELIMITER ;
注意,在Mysql中还有另一个IF。它是一个可以在select语句中使用的函数。