一段SQL語句(涉及游標)

2021-05-07 12:24:16 字數 2580 閱讀 2547

--建立臨時表

create table #people

(pname nvarchar(30)

)insert #people values('4479')

insert #people values('542')

insert #people values('543')

declare @randdate datetime,@randdate1 datetime, @count int,@sdate  datetime,@edate datetime,@sdate1  datetime,@edate1 datetime,@pname char(5),@nowdate datetime

--set @count=(select count(*) from  yskqnew where sj>(select convert(varchar(10),getdate(),120)) and bh='04479')

--定義隨機時間

set   @sdate   =   '07:50:00'  

set   @edate   =   '07:58:00'

set   @sdate1  =   '17:05:00'

set   @edate1  =   '17:10:00'

set   @nowdate= (select convert(varchar(10),getdate(),120))

--生成當天日期+隨機時間

set @randdate=(select convert(varchar(10),getdate(),120)+ dateadd(n,rand()*(datediff(n,@sdate,@edate)),@sdate))

set @randdate1=(select convert(varchar(10),getdate(),120)+ dateadd(n,rand()*(datediff(n,@sdate1,@edate1)),@sdate1))

--建立游標,逐行取臨時表中資料

declare pname_cursor  cursor

for select pname from #people where pname in('4479','542','543')

for read only

open pname_cursor

begin

fetch next from pname_cursor into @pname

while(@@fetch_status=0)

begin

--取當天已insert資料

set @count=(select count(*) from  yskqnew where sj>(select convert(varchar(10),getdate(),120)) and bh=@pname)

--有資料時刪除已有資料並insert自定義資料,無資料時直接insert自定義資料

if(@count<>0)

begin --判斷表中是否存在加班資料,若沒有,執行delete&insert,若有則只delete上午刷卡資料,保留加班刷卡資料,並insert自定義8:00刷卡資料

if not exists(select * from yskqnew where bh=@pname and sj>(select convert(varchar(10),getdate(),120)+' 18:00:00'))

begin

delete from yskqnew where bh=@pname and sj>(select convert(varchar(10),getdate(),120));

insert into yskqnew (bh,rq,sj,jh,bc) values (@pname,@nowdate,@randdate,1,'1');

insert into yskqnew (bh,rq,sj,jh,bc) values (@pname,@nowdate,@randdate1,1,'1');

endelse

begin

delete from yskqnew where bh=@pname and sj>(select convert(varchar(10),getdate(),120)+' 18:00:00');

insert into yskqnew (bh,rq,sj,jh,bc) values (@pname,@nowdate,@nowdate+' 22:02:00',1,'1');

endend

else

begin

insert into yskqnew (bh,rq,sj,jh,bc) values (@pname,@nowdate,@randdate,1,'1');

insert into yskqnew (bh,rq,sj,jh,bc) values (@pname,@nowdate,@randdate1,1,'1')

endfetch next from pname_cursor into @pname

endclose pname_cursor

deallocate pname_cursor

endtruncate table #people--斷開並刪除臨時表

drop table #people

一段SQL指令碼

create table gc col1 char 10 drop table gc 處理引數 declare str varchar 100 select str 1,2,3,4,5 插入處理 declare s varchar 8000 select s select replace str,u...

一段包含很多基礎的整合的SQL語句

對於業務的生疏和自身sql基礎的薄弱,導致我在工作中出現很多難題。後來同事寫的sql語句,讓我明白sql也是語言,不需要畏懼。下面的sql語句記下來,僅供自己學習和參考。d主表,l子表。按照查詢條件來查詢的話,正常情況下,子表內重覆記錄,那麼子表和主表關聯查詢也會產生重覆記錄。而我必須只要得到最新修...

記錄一段sqlserver儲存過程語句

rocedure dbo p insertvariabledatareal as begin declare id numeric 38,0 tagid nvarchar 36 samptime nvarchar 19 sampstatus numeric 38,0 ta alue nvarchar...