Friday, June 12, 2015

SQL cursor example 2


-- [CRM].[insert] 'dave'

Alter procedure [CRM].[insert]
@LoginId varchar(50)
as

begin
declare @FileId int = null
declare @Sender varchar(200) = null
declare @Recepient varchar(200) = null
declare @RecStatus char(1)
declare @IsProcessed char(1)
declare @ProcessedOn datetime = null
declare @EstProcessedOn datetime = null
declare @ProcessType char(1) = null
declare @TemplateId int = null
declare @SeqNum int = null
declare @OfficeStartTime time
declare @CurrentTime time
declare @Status BIT
 
 select @OfficeStartTime = CONVERT(TIME(0), DATEADD(MINUTE, 60*office_start_time, 0)),
@CurrentTime = CONVERT(VARCHAR(8),GETDATE(),108)
 from mst_comp
 where comp_id = (select comp_id
from mst_user
where login_id = 'ABCA')

--print 'Cursor start'

declare @TrackLogCursor CURSOR

if @CurrentTime < @OfficeStartTime
begin

SET @TrackLogCursor = CURSOR
FOR

select 1 as [file_id],'Shekhar' as Sender,'Satish' as Recepient,'P' as rec_status,'N' as is_processed,tl.tr_end_dt as processed_on,
  tl.tr_end_dt as est_processed_on,'S' as process_type,1 as template_id,tl.tr_seq_num
from trn_track tl
where tl.tr_date is null and CONVERT(DATE, tl.tr_end_dt) = CAST(CURRENT_TIMESTAMP AS DATE)

end
  else if @CurrentTime > @OfficeStartTime
begin

SET @TrackLogCursor = CURSOR
FOR

select 1 as [file_id],'Shekhar' as Sender,'Satish' as Recepient,'P' as rec_status,'N' as is_processed,tl.tr_end_dt as processed_on,
  tl.tr_end_dt as est_processed_on,'S' as process_type,1 as template_id,tl.tr_seq_num
from trn_track tl
where tl.tr_date is null and CONVERT(DATE, tl.tr_end_dt) = CAST(CURRENT_TIMESTAMP AS DATE)
 and CAST(lastupd_stamp AS TIME) > @OfficeStartTime
   
end



--print 'Open Cursor'



OPEN @TrackLogCursor

FETCH NEXT FROM @TrackLogCursor INTO @FileId,@Sender,@Recepient,@RecStatus,@IsProcessed,@ProcessedOn,@EstProcessedOn,@ProcessType,@TemplateId,
@SeqNum

WHILE @@FETCH_STATUS = 0

BEGIN

begin


IF EXISTS  (SELECT  1
FROM trn_alert
WHERE tracking_seq_num = @SeqNum and rec_status = 'P')
Update trn_alert
set est_processed_on = @EstProcessedOn,
updated_on = GETDATE()
where tracking_seq_num = @SeqNum

ELSE
 insert into trn_alert([file_id],Sender,Recepient,rec_status,is_processed,processed_on,est_processed_on,process_type,template_id,
               updated_by,updated_on,tracking_seq_num)
 values(@FileId,@Sender,@Recepient,@RecStatus,@IsProcessed,@ProcessedOn,@EstProcessedOn,@ProcessType,@TemplateId,@LoginId,GETDATE(),@SeqNum)

end  


FETCH NEXT FROM @TrackLogCursor INTO @FileId,@Sender,@Recepient,@RecStatus,@IsProcessed,@ProcessedOn,@EstProcessedOn,@ProcessType,@TemplateId,
@SeqNum

END

CLOSE @TrackLogCursor

DEALLOCATE @TrackLogCursor

--start cursor for insert update record in table

end

No comments:

Post a Comment