January 31, 2014 at 1:09 pm
I have a table with Month , Year as varchar. I realized it was a big mistake. Since its getting too complicated to query this way.
Year Month Productname
2013 11 ACB
2013 11 CDE
I would now like to add another column called date and store these Year Month as a date to my existing table
Year Month ProductName Date
2013 11 ACB 2013-11-01
2013 11 CDE 2013-11-01
Is there a way I can do it for all the columns of the existing table ??
Please let me know
January 31, 2014 at 1:19 pm
You can add a derived column on the table with a formula as used below:
WITH SampleData([Year], [Month], Productname ) AS(
SELECT '2013', '11', 'ACB' UNION ALL
SELECT '2013', '11', 'CDE'
)
SELECT *, CAST( [Year] + [Month] + '01' AS date)
FROM SampleData
January 31, 2014 at 3:34 pm
Luis Cazares (1/31/2014)
You can add a derived column on the table with a formula as used below:
WITH SampleData([Year], [Month], Productname ) AS(
SELECT '2013', '11', 'ACB' UNION ALL
SELECT '2013', '11', 'CDE'
)
SELECT *, CAST( [Year] + [Month] + '01' AS date)
FROM SampleData
And make sure the column is a PERSISTED column so that you can index it and the column isn't recalculated every time you read it.
--Jeff Moden
Change is inevitable... Change for the better is not.
January 31, 2014 at 5:14 pm
Try
ALTER TABLE table
ADD [Date] date;
go
UPDATE table
set [Date]= DateFromParts(cast([Year] as int), cast([Month] as int), 1);
go
/*
ALTER TABLE table
DROP COLUMN [Year], [Month];
*/
or
ALTER TABLE table
add [Date] as DateFromParts(cast([Year] as int), cast([Month] as int), 1) persisted;
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply