How to store TOP 2 variables in SQL Server 2008?

435855 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?

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.

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.
  • 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)

    79,775 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.

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

Following

Share this item with your network: