|
|
|
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 );
BEGIN TRAN; UPDATE T1 SET T1.cnt = T1.cnt + 1 FROM T2 WHERE T1.i = T2.i;
SELECT T1.i , T1.cnt FROM T1;
ROLLBACK;
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;
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 ) |
|
|