Friday, August 19, 2011

MSSQL : Need To Update the Date of your records??

Ever had a situation where your terminal had an incorrect date/time  - which causes the entries from that terminal to have wrong date stored inside your DB?


Well, here's an example of the script to update those records. In the example, I only need to update the day of the date. I need to change only the day of those dates to 18th.


declare @startID as Integer --beginning record ID in your list to update
declare @endID as Integer   --last recordID in your list to update
declare @currID as Integer --id as counter
declare @tempD as DateTime --temporary date
declare @dateString as varchar(50) --new Date to be update in String format.


Set @startID = 16883
Set @endID = 16897
Set @currID = @startID


while (@currID <= (@endID) )
BEGIN
select @tempD=thedate from tbl_x where record_id= @currID
PRINT @currID
PRINT @tempD
--construct the Date String (Ammend this to whatever format of date you prefer
Set @dateString = cast(datepart(yy,@tempD) as varchar) + '-' + cast(datepart(mm,@tempD) as varchar)  + '-' + '18' + ' ' + cast(datepart(hh,@tempD) as varchar) + ':' + cast(datepart(mi,@tempD) as varchar) + ':' + cast(datepart(ss,@tempD) as varchar)  
PRINT @dateString
--Update your table
update tbl_x set tbl_thedate=@dateString where record_id= @currID
Set @currID = @currID + 1 
END
GO

No comments:

Post a Comment