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
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.
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.
You can reverse the ordering by using DESC instead of ASC at the end of your query.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With