-- First solution: date is stored and day, month, year and quarter are computed
DECLARE @Table1 TABLE (
Dt DATE NOT NULL,
DD AS CONVERT(TINYINT, DATEPART(DAY, Dt)) PERSISTED,
MM AS CONVERT(TINYINT, DATEPART(MONTH, Dt)) PERSISTED,
YYYY AS CONVERT(SMALLINT, DATEPART(YEAR, Dt)) PERSISTED,
QQ AS CONVERT(TINYINT, DATEPART(QUARTER, Dt)) PERSISTED
);
INSERT @Table1
VALUES (GETDATE());
SELECT * FROM @Table1;
-- Second solution: day, month and year are stored and date and quarter are stored
DECLARE @Table2 TABLE (
Dt AS CONVERT(DATE, DATEADD(DAY, DD-1, DATEADD(MONTH, MM-1, DATEADD(YEAR, YYYY-1, CONVERT(DATE, '00010101',112))))) PERSISTED,
DD TINYINT NOT NULL CHECK(DD BETWEEN 1 AND 31),
MM TINYINT NOT NULL CHECK(MM BETWEEN 1 AND 12),
YYYY SMALLINT NOT NULL CHECK(YYYY BETWEEN 1 AND 9999),
QQ AS CONVERT(TINYINT, ((MM-1)/3)+1) PERSISTED
);
INSERT @Table2 (DD, MM, YYYY)
VALUES (9,3,2013);
SELECT * FROM @Table2;
结果:
Dt DD MM YYYY QQ
---------- ---- ---- ------ ----
2013-03-09 9 3 2013 1
Dt DD MM YYYY QQ
---------- ---- ---- ------ ----
2013-03-09 9 3 2013 1