December 3, 2010 at 9:43 am
How can I convert the CalDate column into a Date type column(SQL Server 2008)? I need the CalDate column to be a Date datatype rather than DateTime as this script will produce:
CREATE TABLE [dbo].[MyTable](
[MyTableId] [bigint] NOT NULL,
[MyDate] [datetime] NOT NULL,
[CalDate] AS (dateadd(day,datediff(day,(0),[ModDate]),(0))) PERSISTED NOT NULL,
CONSTRAINT [MyTablePK] PRIMARY KEY CLUSTERED
(
[MyTableId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[MyTable] WITH NOCHECK ADD CONSTRAINT [MyTableFK.MyTableId] FOREIGN KEY([MyTableId])
REFERENCES [dbo].[MyMainTable] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[MyTable] NOCHECK CONSTRAINT [MyTableFK.MyTableId]
GO
ALTER TABLE [dbo].[MyTable] ADD CONSTRAINT [MyTableDF.MyDate] DEFAULT (getdate()) FOR [ModDate]
GO
Thank you in advance!
December 3, 2010 at 9:45 am
just alter the definition of the computed column so it includes a cast or convert;
however, since a DATE datatype doesn't have the time portion, i think you could get rid of the whole dateadd/datediff stuff.
[CalDate] AS CONVERT(date,(dateadd(day,datediff(day,(0),[ModDate]),(0))) ) PERSISTED NOT NULL,
/*--results
2010-12-03
*/
select convert(date,getdate())
[CalDate] AS CONVERT(date[/b[ModDate] ) PERSISTED NOT NULL,
Lowell
December 6, 2010 at 8:12 am
Lowell,
Thank you for your help!
Your solution worked!
Lilly
December 6, 2010 at 9:39 pm
Lowell (12/3/2010)
just alter the definition of the computed column so it includes a cast or convert;however, since a DATE datatype doesn't have the time portion, i think you could get rid of the whole dateadd/datediff stuff.
[CalDate] AS CONVERT(date,(dateadd(day,datediff(day,(0),[ModDate]),(0))) ) PERSISTED NOT NULL,
/*--results
2010-12-03
*/
select convert(date,getdate())
[CalDate] AS CONVERT(date[/b[ModDate] ) PERSISTED NOT NULL,
If it were for DATETIME instead of just DATE, you don't need the DATEADD. Just convert the DATEDIFF to a DATETIME. Saves a couple of clock cycles for large updates. 🙂
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply