mysql預存程序 在動態SQL內擷取傳回值的方法詳解

來源:互聯網
上載者:User

MySql通用分頁預存程序
過程參數
複製代碼 代碼如下:p_cloumns varchar(500),p_tables varchar(100),p_where varchar(4000),p_order varchar(100),p_pageindex int,p_pagesize int,out p_recordcount int,out p_pagecount int

$:begin
declare v_sqlcounts varchar(4000);
declare v_sqlselect varchar(4000);
#拼接查詢總記錄的SQL語句
set v_sqlcounts = concat('select count(*) into @recordcount from ',p_tables,p_where);
#select v_sqlcounts;leave $;
set @sqlcounts = v_sqlcounts;
prepare stmt from @sqlcounts;
execute stmt;
deallocate prepare stmt;
#擷取動態SQL語句傳回值
set p_recordcount = @recordcount;
#根據總記錄跳數計算出總頁數
set p_pagecount = ceiling((p_recordcount+0.0)/p_pagesize);
if p_pageindex <1 then
set p_pageindex = 1;
elseif p_pageindex > p_pagecount and p_pagecount <> 0 then
set p_pageindex = p_pagecount;
end if;
#拼接分頁查詢記錄的動態SQL語句
set v_sqlselect = concat('select ',p_cloumns,' from ',p_tables,p_where,if(p_order is not null,p_order,''),' limit ',(p_pageindex-1)*p_pagesize,' , ',p_pagesize);
#select v_sqlselect;leave $;
set @sqlselect = v_sqlselect;
prepare stmtselect from @sqlselect;
execute stmtselect;
deallocate prepare stmtselect;
end $

複製代碼 代碼如下:#拼接查詢總記錄的SQL語句
set v_sqlcounts = concat('select count(*) into @recordcount from ',v_tables,v_where);
set @sqlcounts := v_sqlcounts;
#預先處理動態SQL
prepare stmt from @sqlcounts;
#傳遞動態SQL內參數
set @s1= categoryid;
execute stmt using @s1;
deallocate prepare stmt;
#擷取動態SQL語句傳回值
set recordcount = @recordcount;

#拼接查詢總記錄的SQL語句
set v_sqlcounts = concat('select count(*) into @recordcount from ',v_tables,v_where);
set @sqlcounts := v_sqlcounts;
#預先處理動態SQL
prepare stmt from @sqlcounts;
#傳遞動態SQL內參數
set @s1= categoryid; execute stmt using @s1; deallocate prepare stmt;
#擷取動態SQL語句傳回值
set recordcount = @recordcount;
以上我上再做預存程序分頁裡用到動態SQL裡將查詢到的count記錄條數通過變數@recordcount放到recordcount裡面了。
mysql的IF ELSE和其他資料庫的判斷有點不一樣,簡單的判斷語句如下。複製代碼 代碼如下:#根據總記錄跳數計算出總頁數
set pagecount = ceiling((recordcount+0.0)/pagesize);
if pageindex <1 then
set pageindex = 1;
elseif pageindex > pagecount then
set pageindex = pagecount;
else
select pageindex,pagecount;
end if;

#根據總記錄跳數計算出總頁數 set pagecount = ceiling((recordcount+0.0)/pagesize); if pageindex <1 then set pageindex = 1; elseif pageindex > pagecount then set pageindex = pagecount; else select pageindex,pagecount; end if;

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.