본문 바로가기

DB/MS SQL

[Cursor] is loop for a list, how to use

where is the table structure with data.


Now Create a Cursor which travels each record by TransactionId.


-- ================================================
-- This is an example of Cursor
-- ================================================

USE [ApressFinancial]	--.[TransactionDetails].[Transactions]

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Chris
-- Create date:  December,12,2011
-- Description:	just display simple lsit by cursor
-- =============================================

DECLARE @name nvarchar(100);
DECLARE @transid bigint;

DECLARE db_cursor_name CURSOR FOR
	SELECT TransactionId FROM [TransactionDetails].[Transactions];

OPEN db_cursor_name
FETCH NEXT FROM db_cursor_name INTO @transid;

WHILE @@FETCH_STATUS = 0
BEGIN
--	SELECT @name = CustomerFirstName+','+CustomerLastName FROM [CustomerDetails].[Customers] WHERE CustomerId = @custid;
	
	select transactiontype,dateentered,amount from [TransactionDetails].[Transactions]
	WHERE TransactionId = @transid;
	
	FETCH NEXT FROM db_cursor_name INTO @transid;
END

CLOSE db_cursor_name;
DEALLOCATE db_cursor_name;
GO


The result is