MySQL-多条件拼接语句

BEGIN
SET @baseStr= "SELECT * FROM tbName WHERE 1=1 ";
SET @_where="";
IF 1=1 THEN
  SET @_where= CONCAT(@_where," AND sourcedomain="www.baidu.com" ");
END IF;

IF 2=2 THEN 
  SET @_where=CONCAT(@_where," AND userId =4444");
END IF;
  SET @sentence =CONCAT(@baseStr,@_where) ; -- 连接字符串生成要执行的SQL语句
  prepare stmt from @sentence; -- 预编释一下。 “stmt”预编释变量的名称,
  execute stmt; -- 执行SQL语句
  deallocate prepare stmt;    -- 释放资源
END

2.out赋值

SET @_rowCount=0; -- 变量
SET @_count =CONCAT("SELECT COUNT(*) INTO @_rowCount ",@baseStr,@_where);
prepare stmt from @_count;
execute stmt;
deallocate prepare stmt;
SET _pageCount=@_rowCount;
原文地址:https://www.cnblogs.com/liuph/p/4549760.html