Database Operations change primary keys, insert loops, and database primary keys
-- Alter table HistoryData drop constraint PK_HistoryData -- delete the primary key
Alter table HistoryData add constraint PK_HistoryData primary key (CollectionTime, Code) -- change the primary key
Delete from HistoryData where CollectionTime between '2017-09-01 00:00:00 'and '2017-11-01 00:00:00' and ID not in (
Select id from (
Select Code, CollectionTime, max (ID) id from HistoryData
Where CollectionTime between '2017-09-01 00:00:00 'and '2017-11-01 00:00:00' group by Code, CollectionTime))
-- Delete duplicate columns.
Loop insert
Declare @ sDate varchar (20)
Declare @ eDate varchar (20)
Declare @ mindate datetime
Declare @ maxdate datetime
Declare @ mindateStr varchar (20)
Declare @ maxdateStr varchar (20)
Set @ sDate = '2017-1-16 06:30:00'
Set @ eDate = '2017-1-16 08:35:00'
Set @ mindate = cast (@ sDate as datetime)
Set @ maxdate = dateadd (mi, 5, @ mindate) -- mi indicates minute, hh hour, day
While @ maxdate <= cast (@ eDate as datetime)
Begin
Set @ mindateStr = convert (varchar (19), @ mindate, 120)
Set @ maxdateStr = convert (varchar (19), @ maxdate, 120)
-- Print (@ mindateStr)
Print (@ maxdateStr)
-- Number of inserts
-- Insert
Insert into HistoryData values (0.1337, '20160301', @ maxdate, 'Iron ', 1, 9001, 0.1337, '20160301', 'n', '', '20160301 ', 'N', 'n', 0, 'n', 'n ')
Set @ mindate = @ maxdate
Set @ maxdate = dateadd (mi, 5, @ maxdate)
End