将日期时间拆分为日期/年/月/日名称和计数年份

时间:2013-05-09 10:06:58

标签: sql sql-server sql-server-2008 triggers

我有问题是通过使用触发器从datetime分割日期,月份,日期名称,当我插入日期时间时,然后在下一列中将分割日期,时间,月份年份和计算年份(以了解该人的年龄)我的数据)可能吗?

例如,如果我插入

INSERT INTO MAN VALUES ('04/06/1982')

然后会像这样

DATETIME                  DATE         MONTH     YEAR      DAYNAME     AGE
04/06/1982 00:00:00       04           06        1982      friday      27

3 个答案:

答案 0 :(得分:1)

试试这个: -

Declare @myDate datetime 
set @myDate='19820604'    --YYYYMMDD


Select @myDate as DateTime,
       datename(day,@myDate) as Date,
       month(@myDate) as Month,
       datename(year,@myDate) as Year,
       Datename(weekday,@myDate) as DayName,
       DATEDIFF ( year , @myDate , getdate() ) as Age

结果

  ╔══════════════════════════════╦══════╦═══════╦══════╦═════════╦══════════╗
  ║           DateTime           ║ DATE ║ MONTH ║ YEAR ║ DAYNAME ║ Age      ║
  ╠══════════════════════════════╬══════╬═══════╬══════╬═════════╬══════════╣
  ║ April, 06 1982 00:00:00+0000 ║    4 ║     6 ║ 1982 ║ Friday  ║       31 ║
  ╚══════════════════════════════╩══════╩═══════╩══════╩═════════╩══════════╝

SQL小提琴Demo

答案 1 :(得分:0)

代码略有改动,以正确显示年龄。

    Select myDate,myDateDate,myDateMonth,myDateYear,myDateDayName, Convert(varchar(50),Age)+ ' Years and '+Convert(varchar(50),nodays) +'days' {Age] from
        (
        Select @myDate as myDate,
               datename(day,@myDate) as myDateDate,
               month(@myDate) as myDateMonth,
               datename(year,@myDate) as myDateYear,
               Datename(weekday,@myDate) as myDateDayName,
               DATEDIFF ( year , @myDate , getdate() ) Age  , 
               DATEDIFF       ( dd , @myDate , getdate() ) -365* DATEDIFF ( year , @myDate , getdate() )   as nodays
        ) As a

由于 阿伦

答案 2 :(得分:0)

这里有两种解决问题的方法:

- 方法1:
您可以在表中添加一些计算列,因此在检索表内容时,将在该时间内计算其他剩余字段。

-- 1.1) Create the base of table 'MAN'
CREATE TABLE [dbo].[MAN](
    [DATETIME] [datetime] NOT NULL
) ON [PRIMARY]
GO

-- 1.2) Insert a record in it
INSERT INTO MAN VALUES ('04/06/1982')
GO

-- 1.3) Add some computed columns
ALTER TABLE MAN
ADD
    [DAY]       AS DATENAME(DAY, [DATETIME]),
    [MONTH]     AS MONTH([DATETIME]),
    [YEAR]      AS DATENAME(YEAR, [DATETIME]),
    [DAYNAME]   AS DATENAME(WEEKDAY, [DATETIME]),
    [AGE]       AS DATEDIFF(YEAR, [DATETIME], GETDATE())
GO

-- 1.4) See the result
SELECT * FROM MAN


- 方法2:
在创建表时,可以添加所需的其余字段,以便在下一阶段添加插入/更新触发器以计算剩余字段并插入/更新它们。

-- 2.1) Create the table 'MAN' with all needed columns
CREATE TABLE [dbo].[MAN](
    [DATETIME]  [datetime]      NOT NULL,
    [DAY]       [int]           NULL,
    [MONTH]     [int]           NULL,
    [YEAR]      [int]           NULL,
    [DAYNAME]   [nvarchar](10)  NULL,
    [AGE]       [int]           NULL
) ON [PRIMARY]
GO

-- 2.2) Create Insert and update triggers in order to calculate the values of the rest fields while inserting/updating
CREATE TRIGGER [dbo].[trCalculateRemainingDateFields] ON MAN
AFTER INSERT, UPDATE
AS
BEGIN   
    SET NOCOUNT ON;

    UPDATE  MAN
    SET
        [DAY]       = DATENAME(DAY, MAN.[DATETIME]),
        [MONTH]     = MONTH(MAN.[DATETIME]),
        [YEAR]      = DATENAME(YEAR, MAN.[DATETIME]),
        [DAYNAME]   = DATENAME(WEEKDAY, MAN.[DATETIME]),
        [AGE]       = DATEDIFF(YEAR, MAN.[DATETIME], GETDATE())

    FROM    Inserted i
    WHERE   i.[DATETIME] = MAN.[DATETIME]
END
GO


-- 2.3) Insert a record in it
INSERT INTO MAN ([DATETIME]) VALUES ('04/06/1985')
GO

-- 2.4) See the result
SELECT * FROM MAN


- 方法3:
创建计算剩余字段的主表视图可能是一个不错的选择。

-- 3.1) Create the base of table 'MAN'
CREATE TABLE [dbo].[MAN](
    [DATETIME] [datetime] NOT NULL
) ON [PRIMARY]
GO

-- 3.2) Insert a record in it
INSERT INTO MAN VALUES ('04/06/1982')
GO

-- 3.3) Create a view which is contained the remaining fields
CREATE VIEW dbo.vMAN
AS
    SELECT  [DATETIME],
            DATENAME(DAY, [DATETIME])               AS [DAY],
            MONTH([DATETIME])                       AS [MONTH],
            DATENAME(YEAR, [DATETIME])              AS [YEAR],
            DATENAME(WEEKDAY, [DATETIME])           AS [DAYNAME],
            DATEDIFF(YEAR, [DATETIME], GETDATE())   AS [AGE]    
    FROM    MAN
GO

-- 3.4) See the result
SELECT * FROM vMAN