x

How do I loop through a result set and populate variables with data??

New to SQL and need some guidance please.

I am trying to loop through a data set using the ROW_NUMBER function. I only care what the data is for the first three results in the result set. Here is my query:

 Select person_id, @GuarTerPayerName = payer_name, @GuarTerPolicyNbr = policy_nbr from 
     (
         Select person_id, payer_name, policy_nbr, ROW_NUMBER() OVER ( order by payer_name) as 'Row_Number', * 
         from person_payer where person_id = @GuarPersonID
     ) as tbl
     Where tbl.Row_Number = 3

I am receiving the following error, which indicates that I can not populate a variable while using ROW_NUMBER. Grrr....
Msg 141, Level 15, State 1, Procedure NCS_GetGuarantorInfo, Line 51 A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

Thoughts as to how I can accomplish this?? As I stated, I am NEW to SQL and trying desperately to learn! Thanks in advance for any input.

more ▼

asked Apr 17 at 07:13 PM in Default

avatar image

cankrum
1

Is the sub-query returning multiple rows? Just confirming.

Apr 18 at 03:45 AM JohnM
(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

Thanks.... I figured it out. Had to use a cursor.

more ▼

answered Apr 18 at 01:59 PM

avatar image

cankrum
1

Most likely, that's absolutely the worst way to do this. My question is, why do you need to populate a variable here? Is it to call another stored procedure or ???

May 06 at 12:22 AM Jeff Moden
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x10

asked: Apr 17 at 07:13 PM

Seen: 58 times

Last Updated: May 06 at 12:22 AM

Copyright 2017 Redgate Software. Privacy Policy