MySQL自定义函数

 set names gbk;
DATE_FORMAT(publish_datetime,'%Y-%m-%d');

select date_format(now(),'%Y年%m月%d日 %H时:%i分:%s秒');

创建一个现实时间的函数:

 create function f1() returns varchar(30)
 return  date_format(now(),'%Y年%m月%d日 %H时%i分%s秒');

 调用这个函数:

 

select f1();

 

CONCAT()函数用于将多个字符串连接成一个字符串,是最重要的mysql函数之一

 

CREATE TABLE employees  
(  
    employee_id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,  
    employee_name VARCHAR(50) NOT NULL,  
    employee_sex VARCHAR(10) DEFAULT '',  
    hire_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    employee_mgr INT(11),  
    employee_salary FLOAT DEFAULT 3000,  
    department_id INT(11)  
); 

 

 

INSERT INTO employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) VALUES ('David Tian','',10,7500,1);  
INSERT INTO employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) VALUES ('Black Xie','',10,6600,1);  
INSERT INTO employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) VALUES ('Moses Wang','',10,4300,1);  
INSERT INTO employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) VALUES ('Rena Ruan','',10,5300,1);  
INSERT INTO employees(employee_name,employee_sex,employee_mgr,employee_salary,department_id) VALUES ('Sunshine Ma','',10,6500,2);

创建函数-根据ID获取员工姓名与员工工资

DELIMITER //  
CREATE FUNCTION GetEmployeeInformationByID(id INT)  
RETURNS VARCHAR(300)  
BEGIN  
    RETURN(SELECT CONCAT('employee name:',employee_name,'---','salary: ',employee_salary) FROM employees WHERE employee_id=id);  
END//  
DELIMITER ;  
SELECT GetEmployeeInformationByID(1) ;

 

CAST()函数的参数是一个表达式,它包括用AS关键字分隔的源值和目标数据类型。

以下例子用于将文本字符串'12'转换为整型: SELECT CAST('12' AS int)

 

 使用函数CONCAT_WS()指定参数之间的分隔符

SELECT CONCAT_WS('_',id,name) AS con_ws FROM info LIMIT 1;返回结果为
+----------+
| con_ws   |
+----------+
| 1_BioCyc |
+----------+

GROUP_CONCAT函数返回一个字符串结果,该结果由分组中的值连接组合而成。

语句 SELECT locus,GROUP_CONCAT(id) FROM info WHERE locus IN('AB086827','AF040764') GROUP BY locus; 的返回结果为
+----------+------------------+
| locus    | GROUP_CONCAT(id) |
+----------+------------------+
| AB086827 | 1,2              |
| AF040764 | 23,24            |
+----------+------------------+

 

posted @ 2017-03-25 23:36  kangjie  阅读(10805)  评论(0编辑  收藏  举报