Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Top into Different Variables

Probably not possible but I thought I would ask;

I want to get the Top and save each into a different variable. I know that it would be possible with 3 selects and taking the 1st, 2nd, 3rd from the Top 3 but I was hoping it might be possible in one statement?

I.E.

Declare @Var1 as int,
Declare @Var2 as int,
Declare @Var3 as int
select Top 3 [SAVE 3 RETURNED RECORDS INTO VARIABLES] from Table
like image 531
windowsgm Avatar asked Oct 23 '13 15:10

windowsgm


People also ask

How do you select top 10 values in SQL?

Example - Using TOP PERCENT keywordSELECT TOP(10) PERCENT contact_id, last_name, first_name FROM contacts WHERE last_name = 'Anderson' ORDER BY contact_id; This SQL SELECT TOP example would select the first 10% of the records from the full result set.

How do I select top 10 rows in MySQL?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement.

What is the opposite of select top in SQL?

You can reverse the ordering by using DESC instead of ASC at the end of your query.


2 Answers

Supposing for demo purposes you want the TOP 3 schema_id FROM sys.objects ORDER BY object_id.

Declare @Var1 as int;
Declare @Var2 as int;
Declare @Var3 as int;


WITH T AS
(
SELECT *,
       ROW_NUMBER() OVER (ORDER BY object_id) RN
FROM sys.objects
)
SELECT @Var1 = MAX(CASE WHEN RN = 1 THEN schema_id END),
       @Var2 = MAX(CASE WHEN RN = 2 THEN schema_id END),
       @Var3 = MAX(CASE WHEN RN = 3 THEN schema_id END)
FROM T 
WHERE RN <= 3;

SELECT @Var1, @Var2, @Var3

It uses ROW_NUMBER to number the rows then pivots them into a single row result that is used in assigning to the variables.

like image 53
Martin Smith Avatar answered Sep 22 '22 19:09

Martin Smith


This is another way:

Declare @Var1 as int, @Var2 as int, @Var3 as int
Declare @rn int = 1

select top(3) @Var1 = case when @rn = 1 then val else @var1 end,
              @Var2 = case when @rn = 2 then val else @var2 end,
              @Var3 = case when @rn = 3 then val else @var3 end,
              @rn += 1 
from t
order by val

select @var1, @var2, @var3
like image 27
Kaf Avatar answered Sep 22 '22 19:09

Kaf