Tuesday, November 09, 2010

Looping through SQL Server ... This has to be saved. To many hours spent.

I know I will have to do this again....

This article describes various methods that you can use to simulate a cursor-like FETCH-NEXT logic in a stored procedure, trigger, or Transact-SQL batch.


Use Transact-SQL Statements to Iterate Through a Result Set

There are three methods you can use to iterate through a result set by using Transact-SQL statements.



One method is the use of temp tables. With this method, you create a "snapshot" of the initial SELECT statement and use it as a basis for "cursoring." For example:

/********** example 1 **********/



declare @au_id char( 11 )



set rowcount 0

select * into #mytemp from authors



set rowcount 1



select @au_id = au_id from #mytemp



while @@rowcount <> 0

begin

set rowcount 0

select * from #mytemp where au_id = @au_id

delete #mytemp where au_id = @au_id



set rowcount 1

select @au_id = au_id from #mytemp

end

set rowcount 0







A second method is to use the min function to "walk" a table one row at a time. This method catches new rows that were added after the stored procedure begins execution, provided that the new row has a unique identifier greater than the current row that is being processed in the query. For example:

/********** example 2 **********/



declare @au_id char( 11 )



select @au_id = min( au_id ) from authors



while @au_id is not null

begin

select * from authors where au_id = @au_id

select @au_id = min( au_id ) from authors where au_id > @au_id

end





NOTE: Both example 1 and 2 assume that a unique identifier exists for each row in the source table. In some cases, no unique identifier may exist. If that is the case, you can modify the temp table method to use a newly created key column. For example:

/********** example 3 **********/



set rowcount 0

select NULL mykey, * into #mytemp from authors



set rowcount 1

update #mytemp set mykey = 1



while @@rowcount > 0

begin

set rowcount 0

select * from #mytemp where mykey = 1

delete #mytemp where mykey = 1

set rowcount 1

update #mytemp set mykey = 1

end

set rowcount 0











-- ================================================


-- Template generated from Template Explorer using:

-- Create Procedure (New Menu).SQL

--

-- Use the Specify Values for Template Parameters

-- command (Ctrl-Shift-M) to fill in the parameter

-- values below.

--

-- This block of comments will not be included in

-- the definition of the procedure.

-- ================================================

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author: Robert Dannelly

-- Create date: 11/09/2010

-- Description: Resubmission Validation

-- =============================================

CREATE PROCEDURE ResubmissionValidation

-- Add the parameters for the stored procedure here

@ImportID int

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;



-- Insert statements for procedure here

DECLARE @ResubmissionTest TABLE

(

[ImportMetricID] [int] NULL,

[ImportID] [int] NULL,

[MetricInstanceID] [int] NULL,

[MetricValue] [varchar](100) NULL,

[NDTR] [varchar](20) NULL,

[MetricValueDate] [datetime] NULL,

[Narrative] [varchar](300) NULL,

[Resubmission] [varchar](50) NULL,

[ImportMetricStatus] [varchar](50) NULL,

[ImportFailureMsg] [varchar](200) NULL,

[CurrentMetricValue] [varchar](50) NULL

)



INSERT INTO @ResubmissionTest (ImportMetricID, ImportID, MetricInstanceID, MetricValue, NDTR, MetricValueDate, Narrative,

Resubmission, ImportMetricStatus, ImportFailureMsg, CurrentMetricValue)

SELECT ImportMetricID, ImportID, MetricInstanceID, MetricValue, NDTR, MetricValueDate, Narrative,

Resubmission, ImportMetricStatus, ImportFailureMsg, CurrentMetricValue FROM tblImportMetric WHERE ImportID = @ImportID --Need to change to Variable



-- This is used for Testing RBD

--SELECT * FROM @ResubmissionTest





DECLARE @ImportMetric_ID char(11), @Resubmission varchar(10)



SELECT @ImportMetric_ID = min(ImportMetricID) FROM @ResubmissionTest





--Begin LOOP

WHILE @ImportMetric_ID is not null

BEGIN

DECLARE @MetricInstanceID int,

@MetricValueDate DateTime



SELECT @MetricInstanceID MetricInstanceID FROM @ResubmissionTest WHERE ImportMetricID = @ImportMetric_ID



SELECT @MetricValueDate MetricValueDate FROM @ResubmissionTest WHERE ImportMetricID = @ImportMetric_ID

-- Be sure to change the values to @MetricInstanceID AND @MetricValueDate

EXECUTE ImportCheckResubmission @MetricInstanceID, @MetricValueDate, @Resubmission OUTPUT



IF @Resubmission = 'Yes'

BEGIN

UPDATE @ResubmissionTest

SET ImportFailureMsg = 'There is an existing value for this metric and interval. Please indicate if it is a resubmission.'

WHERE ImportMetricID = @ImportMetric_ID





SELECT @ImportMetric_ID = min(ImportMetricID) FROM @ResubmissionTest WHERE ImportMetricID > @ImportMetric_ID

END

END



DELETE FROM tblImportMetric WHERE ImportID = @ImportID



INSERT INTO tblImportMetric (ImportID, MetricInstanceID, MetricValue, NDTR, MetricValueDate, Narrative,

Resubmission, ImportMetricStatus, ImportFailureMsg, CurrentMetricValue)

SELECT ImportID, MetricInstanceID, MetricValue, NDTR, MetricValueDate, Narrative,

Resubmission, ImportMetricStatus, ImportFailureMsg, CurrentMetricValue FROM @ResubmissionTest WHERE ImportID = @ImportID --Need to change to Variable





--This is used for Testing

--SELECT * FROM tblImportMetric

END

GO
Post a Comment