遊標使用

CREATE PROC SyncFlagOperate_Proc
AS
BEGIN
-- 聲明表變量,數據存在內存中、沒有索引、沒有索機制、不會生成SQL日誌。適用於較小數據量
DECLARE  @A TABLE(ID INT,ActionType INT,Operator VARCHAR(50),OperateDate DATETIME,
		ItemId INT,FlagId VARCHAR(50),Unit VARCHAR(5),LabId INT,ItemName VARCHAR(500))  
INSERT INTO @A
	SELECT  B1.ID
		,B1.ActionType
		,B1.Operator
		,B1.OperateDate
		,B3.ItemId
		,B2.FlagId
		,B3.Unit
		,B1.LabId
		,B3.ItemName
	FROM [NCLab_ClientOperateLog] AS B1
		LEFT JOIN [NCLab_RfidFlag] AS B2
			ON B1.FlagId = B2.FlagId
		LEFT JOIN [NCLab_Item] AS B3
			ON B2.ItemId = B3.ItemId
	WHERE SignStatus = 0 AND ActionType = 10 AND B2.FlagId IS NOT NULL




DECLARE cursor1 CURSOR Static  -- 遊標遍歷
FOR SELECT * FROM @A

OPEN cursor1  -- 打開遊標
DECLARE @ID INT,@ActionType INT,@Operator VARCHAR(50),@OperateDate DATETIME,
		@ItemId INT,@FlagId VARCHAR(50),@Unit VARCHAR(5),@LabId INT,@ItemName VARCHAR(500)
FETCH NEXT FROM cursor1 INTO 
	@ID,@ActionType,@Operator,@OperateDate,
	@ItemId,@FlagId,@Unit,@LabId,@ItemName  --從遊標變量中讀取值
WHILE (@@FETCH_STATUS=0) --判斷FETCH語句是否執行成功
	BEGIN
	select @LabId,@FlagId,@ItemName,@Operator,@OperateDate,@ID,@OperateDate
		
		FETCH NEXT FROM cursor1 INTO 
	@ID,@ActionType,@Operator,@OperateDate,
	@ItemId,@FlagId,@Unit,@LabId,@ItemName--讀取遊標變量中的數據
	END
END


EXEC SyncFlagOperate_Proc
相關文章
相關標籤/搜索