How to store TOP 2 variables in SQL Server 2008?

54,905 pts.
Tags:
SQL Server 2008
How can I make it so that I can store the top 2 results in 2 variables?

create table t(id int);
insert into t (id) values (1),(2),(3),(4);

declare @id1 int
declare @id2 int

select top 2 @id1 = first id, @id2 = next id
from t

Is there a way to make this happen in one query without using a loop?
ASKED: September 19, 2013  1:14 PM
UPDATED: September 19, 2013  3:28 PM

Answer Wiki

Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Discuss This Question: 1  Reply

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • carlosdl
    Something like this should work:

    declare @id1 int;
    declare @id2 int;
    
    WITH Results AS
    (
        SELECT TOP 2 id,
            ROW_NUMBER() OVER (ORDER BY id) AS RowNum
        FROM t
    )
    select
        @id1 = (select id from Results where RowNum = 1),
        @id2 = (select id from Results where RowNum = 2)

    65,110 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following