SQL SERVER, One thing you should definitely know about the UPDATE statement ...

Hello friends,

Today, waiting for the saturday, we talk about a simple thing that you really should know about the UPDATE statement.

How many times have you seen updates done like this? 

 

       
UPDATE ORDRIG

SET

  NeatPrice = Price * (100-PercDiscount)/100,

  total = NeatPrice * Qty

where

  id = XX
       
 

 

Notice that the result of the second field depends on the result of the first one.
So in this case order matters.

How does SQL Server behave in this case?

Seems difficult but it is more easy than you could image!
 

Just learn this easy rule:

The UPDATE does not see the results of its work.

 

Of course you can tray by yourself doing this simple update:

CREATE TABLE #ORDRIG (ID INT IDENTITY(1,1), PRICE FLOAT, NETPRICE FLOAT)

INSERT INTO #ORDRIG (PRICE,NETPRICE) VALUES (0,0)

UPDATE #ORDRIG SET PRICE = 5, NETPRICE = PRICE


SELECT * FROM #ORDRIG


 




Et voilà!

That's all for today
I wish you a great saturday!
Luca











Previous post:SQL Server, How to execute T-SQL commands from the command line (attention this post may contain easy but useful tips 😏 )

Comments

  1. I feel SQL is actually a sophisticated and vivacious tool to look for whenever one needs to find out solutions to database related operations.Kudos to the blogger for putting this up.

    SQL Server Load Rest API

    ReplyDelete

Post a Comment

I Post più popolari

SQL Server, execution plan and the lazy spool (clearly explained)

SQL Server, datetime vs. datetime2

How to solve EXECUTE Permission denied on object 'sp_send_dbmail'