插入记录并返回主键
ALTER PROCEDURE [dbo].[PrcAddMessage] ( @nQueueID int,@sPatientID varchar(30),@sPatientName varchar(200),@sStudyID varchar(30), @sAppointmentCode varchar(30),@sAppointmentDr varchar(30),@sAppointmentDrID varchar(30), @dtAppointmentTime DateTime,@sRoomName varchar(30),@nState int,@nMessageID int output,@nOrder int output ) AS begin declare @nStartNum int declare @nStep int declare @nCurrentOrder int select @nStartNum=StartNum,@nStep=Step from B_QueueTable where ID=@nQueueID if @nStartNum is NULL return if @nStartNum is NULL return select @nCurrentOrder=ISNULL(MAX([Order]),0) from B_MessageTable where QueueID=@nQueueID if (@nCurrentOrder <=0) begin set @nCurrentOrder = @nStartNum end else begin set @nCurrentOrder = @nCurrentOrder+@nStep end begin insert into B_MessageTable(QueueID,PatientID,PatientName,StudyID,AppointmentCode,AppointmentDr,AppointmentDrID,AppointmentTime,RoomName,[State],[Order]) values(@nQueueID,@sPatientID,@sPatientName,@sStudyID,@sAppointmentCode,@sAppointmentDr,@sAppointmentDrID,@dtAppointmentTime,@sRoomName,@nState,@nCurrentOrder) end select @nMessageID=SCOPE_IDENTITY() select @nOrder=[Order] from B_MessageTable where ID=@nMessageID end
更新记录与事务
create PROCEDURE [dbo].[ProcMove] ( @nMessageID int,@nMoveFlag int ,@nMoveCount int ) AS BEGIN declare @destOrder int declare @sourceOrder int declare @currentMessageID int declare @currentOrder int declare @nStep int declare @nQueueID int select @sourceOrder=[Order],@nQueueID=QueueID from B_MessageTable where ID=@nMessageID if @nQueueID is null return if @sourceOrder is null return select @nStep=Step from B_QueueTable where ID=@nQueueID if @nStep is null return if(@nMoveFlag=0) begin begin transaction set @destOrder=@sourceOrder-@nMoveCount declare Select_cursor cursor for select ID,[Order] from B_MessageTable where ([Order]>=@destOrder) and ([Order]<@sourceOrder) Order by [Order] asc Open Select_cursor FETCH NEXT FROM Select_cursor INTO @currentMessageID,@currentOrder WHILE @@FETCH_STATUS=0 begin update B_MessageTable set [Order]=@currentOrder+@nStep where ID=@currentMessageID FETCH NEXT FROM Select_cursor INTO @currentMessageID,@currentOrder end close Select_cursor DEALLOCATE Select_cursor update B_MessageTable set [Order]=@destOrder where ID=@nMessageID commit transaction end else begin begin transaction set @destOrder=@sourceOrder+@nMoveCount declare Select_cursor cursor for select ID,[Order] from B_MessageTable where ([Order]<=@destOrder) and ([Order]>@sourceOrder) Order by [Order] asc Open Select_cursor FETCH NEXT FROM Select_cursor INTO @currentMessageID,@currentOrder WHILE @@FETCH_STATUS=0 begin update B_MessageTable set [Order]=@currentOrder-@nStep where ID=@currentMessageID FETCH NEXT FROM Select_cursor INTO @currentMessageID,@currentOrder end close Select_cursor DEALLOCATE Select_cursor update B_MessageTable set [Order]=@destOrder where ID=@nMessageID commit transaction end END