1. 程式人生 > >MySQL使用者變數-預處理語句(動態語句用法)

MySQL使用者變數-預處理語句(動態語句用法)

預製語句的SQL語法基於三個SQL語句:

PREPARE stmt_name FROM preparable_stmt;
 
EXECUTE stmt_name [USING @var_name [, @var_name] ...];
 
{DEALLOCATE | DROP} PREPARE stmt_name;


表結構:

Table: tab1

Columns:
ID bigint(20)
Name

varchar(50)

資料

 ID, Name
'1', '中'
'2', '中國'
'3', '中國風'
#搭建測試環境
drop table if exists tab1;
create table tab1(ID bigint,Name nvarchar(50));
insert into tab1(ID,Name)values(1,"中"),(2,'中國'),(3,'中國風');

#列值傳參條件
set @id=1;
set @Sql=concat('select ID,Name from tab1 where ID=?');
prepare stmt from @sql;
execute stmt using @id;
DEALLOCATE PREPARE stmt;# 或用 drop PREPARE stmt

/*
# ID, Name
'1', '中'
*/

#列值傳參多條件,引數順序按"?"順序傳參
set @id1=1,@id2=2;
set @Sql=concat('select ID,Name from tab1 where ID between ? and ?');
prepare stmt from @sql;
execute stmt using @id1,@id2;
DEALLOCATE PREPARE stmt;# 或用 drop PREPARE stmt
/*
# ID, Name
'1', '中'
'2', '中國'
*/

#動態表名傳參用法
set @TabName="tab1",@id=2;
set @Sql=concat('select ID,Name from ',@TabName,' where ID=?');
prepare stmt from @sql;
execute stmt using @id;
DEALLOCATE PREPARE stmt;# 或用 drop PREPARE stmt
/*
# ID, Name
'2', '中國'
*/

#結果集顯示列傳參用法同表名方法一樣,需要先拼接SQL語句

set @TabName="tab1",@id=3,@Cols='ID,Name';
set @Sql=concat('select ',@Cols,' from ',@TabName,' where ID=?');
prepare stmt from @sql;
execute stmt using @id;
DEALLOCATE PREPARE stmt;# 或用 drop PREPARE stmt
/*
# ID, Name
'3', '中國風'
*/