Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Wrong usage of UPDATE FROM clause.

Total Hit ( 1519)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


This script demonstrates the wrong usage of UPDATE statement with a FROM clause esp. in case of a table with 1-to-many relationship with another tables(s).

Click here to copy the following block
USE tempdb;
go
CREATE TABLE T1 ( i int PRIMARY KEY , cnt int );
INSERT T1 VALUES( 1 , 0 );

CREATE TABLE T2 ( i int REFERENCES T1( i ) , j int );
INSERT T2 VALUES( 1, 1 );
INSERT T2 VALUES( 1, 2 );

-- Objective:
/*
To update the CNT value in T1 with the number of rows
for each i in table T2. Sounds simple enough!
But one common mistake is to use the UPDATE statement
with a FROM clause like:
*/

BEGIN TRAN;
UPDATE T1
SET T1.cnt = T1.cnt + 1
FROM T2
WHERE T1.i = T2.i;

SELECT T1.i , T1.cnt FROM T1;
-- Output after the UPDATE:
/*
i      cnt    
----------- -----------
     1      1
*/

ROLLBACK;

/*
This is not what we expected?!! The problem is because of
the 1-to-many relationship between the tables T1 and T2.
Using the FROM clause & JOIN , both rows from T2 qualify for
the UPDATE criteria & hence only one row is used for the UPDATE
and the T1( Cnt ) value ends up with 1 & not 2.
Please see BOL "UPDATE" topic also for more details.
*/

-- The correct way to code this is to do the following:
BEGIN TRAN;
UPDATE T1
SET T1.Cnt = COALESCE( ( SELECT COUNT( * ) FROM T2
            WHERE T2.i = t1.i ) , 0 )
SELECT T1.i , T1.cnt FROM T1;
/*
i      cnt    
----------- -----------
     1      2
*/

ROLLBACK;
GO
DROP TABLE t2;
DROP TABLE t1;


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.