SQL SERVER游標操作

2022-01-30 02:08:37 字數 2064 閱讀 9294

前幾天一朋友做資料分析,資料來源是excel的,他們作分析都編寫vba指令碼來分析,其中有乙個問題問了我下,我看了之後感覺處理資料分析完全可以匯入到資料庫做分析,編寫vba來分析感覺怪怪(不過也有好處,可以直接把生成的資料轉化成圖形)。其中乙個要求是這樣的,某一車站從早上第一班車到晚上最後一班車,期間不斷有人刷卡上車,要分析出每5分鐘內有多少人上車。我拿過excel表,只有一列資料有效,我把它匯入到sql server裡,如下圖:

資料格式是存的是有點類似時間戳型別的,先要轉換成標準的時間格式,簡單處理下可以了,增加一列好了

update 西直門站 set pullintime=substring(進站時間,1,4)+'-'+substring(進站時間,5,2)+'-'+substring(進站時間,7,2)+' '+substring(進站時間,9,2)+':'+substring(進站時間,11,2)  要求精確到分就可以了,秒就不轉換了,轉換後的格式如下:

該站的首發班車時間是凌晨5點,末班是晚上零點,首先可以構造乙個時間的區間段表,如下

--構造區間段

declare @daybegin datetime,@dayend datetime

declare @table table(starttime datetime,endtime datetime)

set @daybegin = '2009-6-23 5:00'

set @dayend = '2009-6-24 0:00'

while @daybegin <=@dayend

begin

insert @table select @daybegin,dateadd(mi,5,@daybegin)  --每5分鐘乙個間隔

set @daybegin=dateadd(mi,5,@daybegin)

end

--select * from @table  執行後資料如下

區間段分好了,就可以想到每取出乙個時間段,然後在上車時間記錄表裡查詢有多少條記錄在該段時間內就行了,可以考慮用游標。

declare s cursor  --declare 建立游標

static

for select starttime,endtime from @table

--定義變數

declare @starttime datetime,@endtime datetime

declare @temptable table(starttime datetime,endtime datetime,number int)

open s  --開啟游標

fetch next from s into @starttime,@endtime --提取上次提取行的下一行

while(@@fetch_status = 0)

begin

insert @temptable select isnull(max(@starttime),@starttime),isnull(max(@endtime),@endtime), count(*) from 西直門站 where pullintime > @starttime and pullintime <=@endtime

--這裡就不能用between and了,不然分隔的時間點上車的人數會在相鄰的兩個區間段重複計數,另外第一班車的上車時間等於@starttime 沒有計進去,這裡不影響總體分析,當然可以做個標記,讀乙個區間段時用between...and...就可以了

fetch next from s into @starttime,@endtime

endclose s  --關閉游標

deallocate s  --刪除游標,釋放資源

select * from @temptable

最後執行的結果如下:

mysql游標很慢 Sqlserver 游標 慢

net專案中有個模組做統計功能,原先方法速度很慢,所以需要改進,統計結果如下圖 下圖接上圖後面 原先的處理方式是,這些資料分別涉及到四五張表,前台從資料庫中查詢出需要的資料集,然後分別遍歷這些資料集拼接html字串顯示在介面上。優化思考 net專案中有個模組做統計功能,原先方法速度很慢,所以需要改進...

SQL Server 游標使用

游標概念 資料庫操作中我們常常會遇到這樣情況,即從某一結果集中逐一地讀取一條記錄。那麼如何解決這種問題呢?游標為我們提供了一種極為優秀的解決方案。游標 cursor 是系統為使用者開設的乙個資料緩衝區,存放sql語句的執行結果。每個游標區都有乙個名字。使用者可以用sql語句逐一從游標中獲取記錄,並賦...

sqlserver游標使用

create procedure pk test as 宣告2個變數 declare o id nvarchar 20 declare a salary float 宣告乙個游標mycursor,select語句中引數的個數必須要和從游標取出的變數名相同 declare mycursor curso...