This morning I needed to compose a very simple SQL routine and it took me around five compiles until I got the syntax right.  All I needed to do was transfer an active status from one entity (in my case a computer) to another.  I decided to implement this by updating the same table in which I was selecting.  I think the syntax associated with “self update” type queries is tricky so this post is so I personally don’t lose this code snippet and future cycles.  I hope it might help you as well.

This example transfers the status of the source computer to the destination computer.  Nothing fancy…

DECLARE @SourceID INT; SET @SourceID = 2
DECLARE @DestinationID INT; SET @DestinationID = 1

DECLARE @Computer TABLE (ComputerID INT, StatusID INT)

INSERT INTO @Computer(ComputerID, StatusID)
SELECT @DestinationID, 1 UNION SELECT @SourceID, 2

SELECT * FROM @Computer

UPDATE A
SET A.StatusID = B.StatusID
FROM @Computer A, @Computer B
WHERE B.ComputerID = @SourceID
AND A.ComputerID = @DestinationID

SELECT * FROM @Computer

(2 row(s) affected)
ComputerID  StatusID
----------- -----------
1           1
2           2

(2 row(s) affected)

(1 row(s) affected)

ComputerID  StatusID
----------- -----------
1           2
2           2

(2 row(s) affected)

 

kick it on DotNetKicks.com

4 Comments to “TSQL – Self Update”

  1. Very nice design and style and fantastic subject matter, very little else we need :D .

  2. Ive been meaning to study this and only never acquired a chance. Its an element that Im really interested in, I simply started reading and Im glad I did. Youre a fantastic blogger, one of many ideal that Ive seen. This blog absolutely has some information on topic that I just wasnt aware about. Thanks for bringing these materials to light.

  3. Extermely informative publish here. Thanks for sharing your knowledge with me. I will certainly be back.

  4. Robt Aldaco says:

    Hi there. Mainly would like to place a quick remark and enquire where you obtained your web publication layout I will be setting up own blog and truly really like your specific model.

Leave a Reply

You can wrap your code with [ruby][/ruby] or [python][/python] blocks for syntax highlighting and you can use these traditional tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>