In T-SQL, I am trying to insert values in a date table, US & French dates. When table is created with columns as DATE, the insert does not work, it errors.
When I switch to VARCHAR(12) instead of DATE for those columns, INSERT works fine
My server is windows 2012, english Microsoft SQL Server 2016 (SP2-CU10) (KB4524334) - 13.0.5492.2 (X64), regional settings France I googled but not able to find a solution.
Here are 3 scripts, 1st one is the table with columns with DATE type (with which insert statement fails)
CREATE TABLE [dbo].[DimDateTest](
[ShortDate] [date] NULL,
[FullDate] [varchar](20) NULL,
[MonthShortName] [varchar](10) NULL,
[MonthLongName] [varchar](15) NULL,
[FrenchShortYear] [date] NULL,
[FrenchUSLongYear] [date] NULL,
[FrenchLongYear] [date] NULL,
[DateAge] [varchar](20) NULL
) ON [PRIMARY]
GO
Here is the insert statement:
INSERT dbo.DimDateTest
( ShortDate, FullDate, MonthShortName, MonthLongName, FrenchShortYear, FrenchUSLongYear, FrenchLongYear, DateAge)
SELECT CAST(DATEADD(dd, Number.n-1, '1/1/2015') AS DATE)
,CAST(DATENAME(mm, DATEADD(dd, Number.n-1, '1/1/2015')) AS VARCHAR(10)) + ' ' + CAST(DATEPART(dd, DATEADD(dd, Number.n-1, '1/1/2015')) AS VARCHAR(2)) + ', ' + CAST(YEAR(DATEADD(dd, Number.n-1, '1/1/2015')) AS VARCHAR(4))
,CAST(DATENAME(mm, DATEADD(dd, Number.n-1, '1/1/2015')) AS VARCHAR(10))
,CAST(DATENAME(mm, DATEADD(dd, Number.n-1, '1/1/2015')) AS VARCHAR(10)) + ' ' + CAST(YEAR(DATEADD(dd, Number.n-1, '1/1/2015')) AS VARCHAR(4))
, CONVERT(date, CAST(DATEADD(dd, Number.n-1, '1/1/2015') as datetime), 5) as FrenchShortYear
, FORMAT( CAST(DATEADD(dd, Number.n-1, '1/1/2015') as date), 'dd/MM/yyyy', 'fr-FR' ) AS 'FrenchUSLongYear'
, CONVERT(VARCHAR(12), CAST(DATEADD(dd, Number.n-1, '1/1/2015') as date), 7) as 'FrenchLongYear'
,
CASE WHEN DATEADD(dd, Number.n-1, '1/1/2015') BETWEEN '1/1/2015' AND '3/31/2015' THEN 'Age of Goats'
WHEN DATEADD(dd, Number.n-1, '1/1/2015') BETWEEN '4/1/2015' AND '4/30/2015' THEN 'Age of Copper'
ELSE 'Age of the Unknown'
END
FROM dbo.Number
WHERE DATEADD(dd, Number.n-1, '1/1/2015') <= '4/30/2020'
ORDER BY Number.n
and here is the error I am getting
Msg 241, Level 16, State 1, Line 13 Conversion failed when converting date and/or time from character string.
When I drop and recreate the table by switching Columns type from DATE to varchar(12), insert works fine, here is the script for the table
CREATE TABLE [dbo].[DimDateTest](
[ShortDate] [date] NULL,
[FullDate] [varchar](20) NULL,
[MonthShortName] [varchar](10) NULL,
[MonthLongName] [varchar](15) NULL,
[FrenchShortYear] [varchar](12) NULL,
[FrenchUSLongYear] [varchar](12) NULL,
[FrenchLongYear] [varchar](12) NULL,
[DateAge] [varchar](20) NULL
) ON [PRIMARY]
GO
NOTE : dbo.Number is a number table populated by numbers from 1 to 10000
What am I doing writing wrong? Thanks for your help