April 19, 2023 at 12:00 am
Comments posted to this topic are about the item Swapping values of variables
God is real, unless declared integer.
April 19, 2023 at 1:38 pm
Thanks for this very instructive question. I didn't realize that the swap works in UPDATE statements - if that had been the question of the day, I would have gotten it wrong.
-- webrunner
-------------------
A SQL query walks into a bar and sees two tables. He walks up to them and asks, "Can I join you?"
Ref.: http://tkyte.blogspot.com/2009/02/sql-joke.html
April 19, 2023 at 1:41 pm
Back to the basics question - love it!
April 19, 2023 at 3:33 pm
Great question and even better explanation, Thomas. Nicely done.
--Jeff Moden
Change is inevitable... Change for the better is not.
April 20, 2023 at 6:55 am
I use this feature a lot, see the following example:
declare @t table (i int identity primary key, name sysname)
declare @i int = 1
,@name sysname
insert into @t
select TOP(10) name
from sys.objects
ORDER BY name
while 1=1
begin
select @name = name
,@i += 1
from @t
where i = @i
if @@ERROR != 0 OR @@ROWCOUNT < 1
break
print @name
end
P.S. In the UPDATE of your explanation, the swap runs as expected because the source (deleted) and the destination (inserted) are different, so, after the assignement the source fields do not change. Instead, the variables are both source and destination.
DECLARE @i INT = 1
, @j INT = 2
CREATE TABLE #tmp (i INT, j INT)
INSERT INTO #tmp (i, j) VALUES (1, 2)
UPDATE #tmp
SET @i = @j
, @j = @i
SELECT @i AS i, @j AS j
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply