BEGIN set @country = country;/**输入的country参数**/
set @type = type;/**输入的节假日类型参数**/
set @_year = _year;/**输入的年份参数**/
set @tempsql = 'SELECT lh.lh_id,wp.location_id,wp.country,lh.starttime,lh.endtime,lh.type from workplace AS wp,legalholiday as lh WHERE wp.location_id=lh.location_id';
/**拼接SQL语句的字符串,注意,这里用SET 和 @ 一定要用@**/
IF(country<>'')
THEN
SET @tempsql=CONCAT(@tempsql,' and wp.country = ''',@country,'''');
END IF;
IF(type<>'')
THEN
SET @tempsql=CONCAT(@tempsql,' and lh.type=''',@type,'''');
END IF;
IF(_year<>'')
THEN
IF(_year<>0)
THEN
SET @tempsql=CONCAT(@tempsql,' and year(lh.starttime)=',@_year,' and year(lh.endtime)=',@_year);
END IF;
END IF;
/**这里可以写上select * from @tempsql 来检查你的SQL拼接是否正确,运行时把它注释就好。但是如果字符串太长的话,可能就看不到了**/
prepare stmt from @tempsql;/**预编译SQL**/
EXECUTE stmt;/**执行SQL**/