[SQL] 查詢連續時間

透過一道指令,直接將時間範圍內清單列出來


 

declare @start table(ControlDate DATE)
declare @end datetime
set @end='2017-01-01'
while @end <='2017-12-31'
begin
insert into @start  select convert(varchar(20),@end,112)
set @end = @end+1
end
select * from @start

 


 

將兩個表單內的資料,抓取所有設備的某一天為基準值,印出到一段時間
TimeControl、TimeDevice
declare @start table(TimeDate date)
declare @end datetime
set @end='2017-01-01'
while @end <='2017-1-02'
begin
insert into @start  select convert(varchar(20),@end,112)
set @end = @end+1
end
SELECT DeviceID, TimeDate, 
Segment, StartTime, EndTime FROM TimeControl ,@start
WHERE DeviceID IN 
(Select DeviceID FROM TimeDevice WHERE PageName = '大樓名稱')
 AND (ControlDate = '2018-01-01抓取時間') order by TimeDate,DeviceID,Segment

DeviceID為表單A
TimeDate為自己迴圈寫出來
其餘為表單B

 


抓取當天日期的語法

  1. YYYY/MM/DD: Convert(varchar(10),Getdate(),111)
  2. YYYYMMDD: Convert(varchar(10),Getdate(),112)
  3. HH:MM:SS: Convert(varchar(8),Getdate(),108)
  4. HH:MM:SS:mmm: Convert(varchar(12),Getdate(),114)
  5. HHMMSS: Replace(Convert(varchar(8),Getdate(),108),':','')
  6. HHMMSSmmm: Replace(Convert(varchar(12),Getdate(),114),':','')
  7. YYYY/MM/DD HH:MM:SS:Replace(Convert(varchar(30),Getdate(),120),'-','/')
  8. YYYY/MM/DD HH:MM:SS:Replace(Convert(varchar(30),Getdate(),121),'-','/')
  9. YYYY/MM/DD HH:MM:SS: Convert(varchar(10),Getdate(),111) + Space(1) + Convert(varchar(8),Getdate(),108)
  10. YYYYMMDDHHMMSS: Convert(varchar(10),Getdate(),112) + Replace(Convert(varchar(8),Getdate(),108),':','')