How to save date values ​​partially?

I am using MS SQL Server 2005, and I need to partially store the date values. For example, the day part of the date may actually remain unknown, but MS SQL Server is limited to specifying the full date, for example:

INSERT foo(dt) VALUES('2001-10-31');

I would like to use something like this:

INSERT foo(dt) VALUES ('2001-10-??');

Of course, MS SQL cannot accept such a date, and I found an example that converts dates to factors:

SET NOCOUNT ON 
CREATE TABLE foo ( 
    dt INT 
) 
INSERT foo VALUES ( 
    DATEPART(YEAR, GETDATE()) * 10000 
        + DATEPART(MONTH, GETDATE()) * 100 
        + DATEPART(DAY, GETDATE()) 
) 
SELECT dt FROM foo 
DROP TABLE foo

... hm, I cannot believe that this is the only way to solve the problem, so I would like to ask: how can I solve this problem in the best way?

Thanks in advance.


UPD 2014:
Also see Saving Partial Dates in a Database

+3
3

- :

CREATE Table PartialDates
(
     YearPart       smallint --(2 bytes -32k to +32k)
    ,MonthPart      tinyint  --(1 byte 0 to 255)
    ,DayPart        tinyint  --(1 byte 0 to 255)
    ,CompleteDate  AS (CONVERT(datetime,CONVERT(varchar(10),YearPart)+'-'+CONVERT(varchar(10),MonthPart)+'-'+CONVERT(varchar(10),coalesce(DayPart,1))))
)
ALTER TABLE dbo.PartialDates ADD CONSTRAINT
    CK_PartialDates_IsDate CHECK (ISDATE(CONVERT(varchar(10),YearPart)+'-'+CONVERT(varchar(10),MonthPart)+'-'+CONVERT(varchar(10),coalesce(DayPart,1)))=1)
GO

insert into PartialDates (yearpart,monthpart,daypart) values(2009,91,1) --error
insert into PartialDates (yearpart,monthpart,daypart) values(2009,1,1)  --ok
insert into PartialDates (yearpart,monthpart,daypart) values(2009,1,51) --error
insert into PartialDates (yearpart,monthpart,daypart) values(2009,2,29) --error
insert into PartialDates (yearpart,monthpart,daypart) values(2009,2,28) --ok
insert into PartialDates (yearpart,monthpart,daypart) values(2009,2,null)--ok

select * from PartialDates

YearPart MonthPart DayPart CompleteDate
-------- --------- ------- -----------------------
2009     1         1       2009-01-01 00:00:00.000
2009     2         28      2009-02-28 00:00:00.000
2009     2         NULL    2009-02-01 00:00:00.000

(3 row(s) affected
+2

, ? , . / , -, .

+2

- , , . , SQL Server , convert:

select cast(convert(varchar, GETDATE(), 112) as int)

, convert int, . varchar, int.

, 00 , :

select cast(convert(varchar, getdate(), 112) as int) - day(getdate())

Hope this helps!

+1
source

Source: https://habr.com/ru/post/1716586/


All Articles