-- 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
請解釋更多。你想要select子句在日,月,季度等分割你的日期列嗎? – DevelopmentIsMyPassion 2013-03-08 23:35:13
我會說離開日期作爲日期字段和選擇查詢,您可以使用日期函數過濾日,月和年。搜索sql服務器日期函數。 – Kaf 2013-03-08 23:36:49