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', '中国风'
*/





你可能感兴趣的:(MySQL-Dev)