下文介紹的MySql存儲過程是帶參數的存儲過程動態執行SQL語句),該MySql存儲過程是根據用戶輸入的條件和排序方式查詢用戶的信息,排序條件可以沒有調用方式:
call GetUsersDynamic('age<=30','');
- /********動態查詢用戶的信息********/
- CREATE PROCEDURE GetUsersDynamic(WhereCondition varchar(500),OrderByExpress varchar(100))
- begin
- declare stmt varchar(2000);
- if LENGTH(OrderbyExpress)>0 then
- begin
- set @sqlstr=concat('select id,name,password,age,getdate(adddate) as AddDate from users where ',WhereCondition,' order by ',OrderByExpress);
- end;
- else
- begin
- set @sqlstr=concat('select id,name,password,age,getdate(adddate) as AddDate from users where ',WhereCondition);
- end;
- end if;
- prepare stmt from @sqlstr;
- execute stmt;
- end;
getdate()是一個自定義的函數,作用是返回日期的短格式
- CREATE DEFINER=`root`@`localhost` FUNCTION `getdate`($date datetime) RETURNS varchar(50) CHARSET latin1
- return date_format($date,'%Y-%m-%d');
動態插入數據的MySql存儲過程,注意四個單引號表示一個一引號):
- CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertUser`(in name2 varchar(50),in password2 varchar(32),in age2 int,in adddate2 datetime)
- begin
- DECLARE stmt varchar(2000);
- set @sqlstr=concat('insert into users(name,password,age,adddate) values(');
- set @sqlstr=concat(@sqlstr,'''',name2,'''',',','''',password2,'''',',',age2,',','''',adddate2,'''',')');
- prepare stmt from @sqlstr;
- execute stmt;
- end;
取得MySQL表信息的語句
mysql插入Clob字段的實例
常見MySql字段的默認長度
MySQL中INSERT的一般用法
MySQL索引類型介紹