以下代码返回员工出生的年份:
CREATE OR REPLACE FUNCTION Convert_Year_to_Year (Convert_Date IN Date)
RETURN Varchar2 AS
BEGIN
RETURN (To_Char (Convert_Date, ‘YEAR’));
END;
/
当我使用SELECT命令检索数据时,将显示以下输出:
Select employee_id, hiredate, Convert_year_to_year (hiredate) AS Year_Hired
FROM employees;
EMPLOYEE_ID HIREDATE YEAR_HIRED
1 12/17/2007 TWO THOUSAND SEVEN
2 02/20/2008 TWO THOUSAND EIGHT
3 02/22/2008 TWO THOUSAND EIGHT
4 04/02/2008 TWO THOUSAND EIGHT
5 09/28/2008 TWO THOUSAND EIGHT
6 05/01/2008 TWO THOUSAND EIGHT
7 06/09/2008 TWO THOUSAND EIGHT
8 12/09/2008 TWO THOUSAND EIGHT
9 09/08/2007 TWO THOUSAND SEVEN
10 01/12/2007 TWO THOUSAND SEVEN
另外,如果我想组合所有RETURN,我该如何编写代码?下面没有用
CREATE OR REPLACE FUNCTION Convert_Year_to_Year (Convert_Date IN Date)
RETURN Varchar2 AS
BEGIN
RETURN (To_Char (Convert_Date, 'YYYY'),
RETURN (To_Char (Convert_Date, 'DAY'),
RETURN (To_Char (Convert_Date, 'D'));
END;
/
EMPLOYEE_ID HIREDATE YEAR_HIRED DAY_HIRED NUMERICAL_DAY_OF_WEEK
1 12/17/2007 2007 MONDAY 1
2 02/20/2008 2008 WEDNESDAY 3
3 02/22/2008 2008 FRIDAY 5
4 04/02/2008 2008 WEDNESDAY 5
5 09/28/2008 2008 SUNDAY 7
答案 0 :(得分:1)
获取数字年份(例如2007
):
TO_CHAR(Convert_Date, 'YYYY')
获取星期几的名称(例如SATURDAY
):
TO_CHAR(Convert_Date, 'DAY')
获取星期几的数值(例如7
):
TO_CHAR(Convert_Date, 'D')
如果你真的以非标准的方式得到一周的数值(例如星期一= 1,星期六= 6,星期日= 7),那么这种丑陋就会起作用:
to_char(decode(to_number(to_char(Convert_Date, 'D')) - 1, 0, 7, to_number(to_char(Convert_Date, 'D')) - 1))
修改强>
要将3位信息作为查询的3个单独列返回,您需要创建3个单独的函数,或者,只需编写此查询而不使用函数,这对您来说无论如何都不会做很多事情(但是你你的函数中不能有3个return
语句:
Select employee_id,
hiredate,
TO_CHAR(hiredate, 'YYYY') AS Year_Hired,
TO_CHAR(hiredate, 'DAY') AS DAY_HIRED,
decode(to_number(to_char(hiredate, 'D')) - 1, 0, 7, to_number(to_char(hiredate, 'D')) - 1) AS NUMERICAL_DAY_OF_WEEK
FROM employees;