I have a table called ColorTable
I want to write a query to retain the latest 30 days of data in the database or table. you can use the Field call ColorTable.DateTime . The column ColorTable.DateTime field is a varchar, its a formated string. thanks
Loading

SenthilkumarRank #387 · 6.5K reputationPosted Mar 12, 2012, 8:22 AM EDT
SELECT * FROM ColorTable WHERE CONVERT(VARCHAR, ColorTable.DateTime , 107) > (GETDATE()-30)
Here i want to make a note of you mentioned the column name is DateTime. But it shouldn't be.
I suggest you to use the same data type. Because it will make unnecessary type casting overload to the server.
If this post is useful then do not forgot to mark it as "Accepted Answer".
David SmithRank #999 · 2K reputationPosted Mar 12, 2012, 9:23 AM EDT
SenthilkumarRank #387 · 6.5K reputationPosted Mar 12, 2012, 7:20 PM EDT
DELETE FROM ColorTable WHERE id NOT IN(SELECT id FROM ColorTable WHERE CONVERT(VARCHAR, ColorTable.DateTime , 107) > (GETDATE()-30))
I have used key column to delete the record. Use your primary key column to replace the id column in the above query.
If it is useful and answered your question then mark it as "Accepted Answer".
Jignesh TrivediRank #16 · 50.3K reputationPosted Mar 12, 2012, 8:07 PM EDT
if your column ColorTable.DateTime is a varchar, then u also consider how you store data in this filed, If you enter this data in UTC (yyyy-MM-dd) format then it easyly convert in to datatime format.
try...
Delete ColorTable where Datediff(d,CAST([DateTime] as Datetime),GETDATE()) < 30
hope this help.
David SmithRank #999 · 2K reputationPosted Mar 12, 2012, 9:06 PM EDT
SenthilkumarRank #387 · 6.5K reputationPosted Mar 12, 2012, 9:28 PM EDT
2012-03-13T10:48:01
Still you want the output of the YYYYMMDD:hhmmss format then
You need to replace the result string like the following.
string str = String.Format("{0:s}", dt).Replace("-", "").Replace(":","").Replace("T", ":");
Mark it as "Accepted Answer" if you found useful.
Jignesh TrivediRank #16 · 50.3K reputationPosted Mar 12, 2012, 9:36 PM EDT
I think no.
if your format YYYYMMDD hh:mm:ss then it is possible to conver in SQL server.
David SmithRank #999 · 2K reputationPosted Mar 12, 2012, 10:19 PM EDT
this is giving me an error below , failed conversion, keep in mind the format thats in the database is 'YYYYMMDD:hhmmss' try this value '20111112:000000'
DELETE
FROM Color
WHERE REPLACE(CONVERT(VARCHAR,Color.CreatedDateTime, 102),'.','/') +' '+ CONVERT(VARCHAR, Color.CreatedDateTime, 108) < (GETDATE()-30)
David SmithRank #999 · 2K reputationPosted Mar 12, 2012, 10:31 PM EDT
Conversion failed when converting date and/or time from character string.
Jignesh TrivediRank #16 · 50.3K reputationPosted Mar 12, 2012, 10:47 PM EDT
Time in ColorTable.DateTime is not more important than
try....
Delete ColorTable where Datediff(d,cast(SUBSTRING ( [DateTime] , 0 , CHARINDEX(':',[DateTime],0)) as datetime),GETDATE()) < 30
hope this help.