mysql日期在where子句中?

时间:2014-04-28 17:24:32

标签: mysql stored-procedures

这是我的存储过程

DELIMITER $$
DROP PROCEDURE IF EXISTS `simplesign`.`GetTenantTaskBetweenDate` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetTenantTaskBetweenDate`(
   IN tid VARCHAR(100), 
   IN fromdate DATE ,
   IN todate DATE, 
   IN searchvalue VARCHAR(100)
)
BEGIN
   SELECT RequestID 
     FROM task 
    WHERE ( (TenantID=tid) 
      AND Create_date BETWEEN fromdate AND todate) 
      AND (File_name LIKE searchvalue || File_title LIKE searchvalue) 
    ORDER BY Create_date DESC;
END $$ 
DELIMITER ;

在以下情况下,我希望ReuestID表中的所有task

  • 如果fromdate和todate为null,则按searchValue
  • 搜索
  • 如果fromdate,todate和searchValue不为null,则按所有三个输入进行搜索
  • 如果fromdate或todate为null,则由searchValue
  • 搜索
  • 如果searchValue为null,则按fromdate和todate
  • 进行搜索
  • 如果所有三个输入都为空,则通常搜索(select * from)

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

听起来你不想使用所有条件,如果它们不是空的

DELIMITER $$
DROP PROCEDURE IF EXISTS `simplesign`.`GetTenantTaskBetweenDate` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `GetTenantTaskBetweenDate`(
   IN tid VARCHAR(100), 
   IN fromdate DATE ,
   IN todate DATE, 
   IN searchvalue VARCHAR(100)
)
BEGIN
   SELECT RequestID 
     FROM task 
    WHERE (tid is null OR TenantID=tid)
      AND (fromdate is null OR Create_date >= fromdate) 
      AND (todate is null OR Create_date <= todate)
      AND (searchvalue is null OR File_name LIKE searchvalue OR File_title LIKE searchvalue) 
    ORDER BY Create_date DESC;
END $$ 
DELIMITER ;