2

So, I discovered something interesting. I was playing around with the TOP command and assigning variables in the select statement. I issued the below query and found that the variable (@a) value was the last value returned from the Top Command. It almost seems like for each value returned, that value is assigned to the variable, then each row in the result set is subsequently assigned, almost like a loop.

declare @a nvarchar(max)

select top 10 DisplayName
from dbo.Users

select top 10 @a = DisplayName
from dbo.Users

select @a as Results

Results:

Result Set 1

This made me curious. I modified the query to test again and executed the following:

declare @a nvarchar(max)
declare @b int = 0

select TOP 10 @a = DisplayName, @b = @b + 1
from dbo.Users

select @a as DisplayName, @b as Number

Results:

Results Image 2

This is really interesting. From these two queries, it almost seems like the TOP command is doing some sort of loop because of the cumulative sum that is happening on @b, as well as the assignments happening above. Can someone explain what is going on? Does SQL do a RBAR operation on when using the TOP command?

EDIT:

I also did this without the TOP commands, and see the results, so it's not just the TOP command. It almost seems like assigning a variable in the SELECT statement does a RBAR command?

declare @a nvarchar(max)
declare @b int = 0

select @a = DisplayName, @b = @b + 1
from dbo.Users

select @a as DisplayName, @b as Number

Results:

Results Image 3

  • @ypercubeᵀᴹ I didn't originally, but I just did now. The result is the same as when using the TOP command. The @b variable is still a cumulative sum, so the question still stands. I'll modify the question to be more general. – MarkAugust Oct 29 at 15:44
6

It almost seems like for each value returned, that value is assigned to the variable, then each row in the result set is subsequently assigned, almost like a loop.

Yep. That's what happens. This is a side-effect of how variable assignment in SELECT queries were initially implemented. But it was used enough that it can't really be changed, and even is documented:

If a SELECT statement returns more than one row and the variable references a non-scalar expression, the variable is set to the value returned for the expression in the last row of the result set.

Variables (Transact-SQL)

and

For backwards compatibility reasons, SQL Server provides support for assignments of type SELECT @p = @p + 1 ... ORDER BY at the top-most scope.

Ordering guarantees in SQL Server

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.