Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update from Temp Table

Query:

SELECT ID, T.c.value('@Address', 'nvarchar(20)' ) as Address
INTO #TMP
FROM TABLE1
    CROSS APPLY XMLData.nodes('/Document') AS T(c)

UPDATE TABLE1
SET HomeAddress = (SELECT TOP 1 t.Address
                   FROM #TMP t
                   WHERE t.ID = ID)

Mainly, I need to copy data OUT from an XML field to normal fields within the same table.

Questions:

  1. Any reason why all the records get the HomeAddress on Table1?
  2. Is really Cursor the only way to update the value on Table1?
like image 899
SF Developer Avatar asked Feb 27 '13 17:02

SF Developer


People also ask

Can you UPDATE a temporary table?

You cannot update rows in a created temporary table, but you can update rows in a declared temporary table. The column to which you assign the null value must not be defined as NOT NULL. An expression, which can be any of the following items: A column.

How do you UPDATE data in an existing table?

The UPDATE statement in SQL is used to update the data of an existing table in database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. UPDATE table_name SET column1 = value1, column2 = value2,...

Which is faster CTE or temp table?

If you are joining multiple tables with millions of rows of records in each, CTE will perform significantly worse than temporary tables. I've seen this from my own experience. CTE's perform significantly slower. CTE's also perform slower because the results are not cached.


2 Answers

On the update, I need to FULLY QUALIFY the Table as follow:                  

UPDATE TABLE1 SET TABLE1.HomeAddress = (SELECT TOP 1 t.Address  
               FROM #TMP t  
               WHERE t.ID = TABLE1.ID)  
like image 112
SF Developer Avatar answered Nov 15 '22 01:11

SF Developer


UPDATE T2
SET HomeAddress = t1.address
FROM TABLE2 t2
join TABLE1 t1 on T1.ID = t2.HomeAddressID
and t2.HomeAddress <> t1.address

Use a join. No need to temp table or correlated subquery.

If table 1 is in a one to many relationshisp these are some posibilites for handling that. If you havea value that indicates one and only one record (we have a field in our system that picks the most important address, it is maintained with a trigger to guarantee uniquesness), the try this:

UPDATE T2
SET HomeAddress = t1.address
FROM TABLE2 t2
join TABLE1 t1 on t1.ID = t2.HomeAddressID
WHERE t1.somefield = 'somevalue'
and t2.HomeAddress <> t1.address

If you need to based the unique record on asome other field (such as the most recent date), then try a variation of this:

UPDATE T2
SET HomeAddress = t1.address
FROM TABLE2 t2
join TABLE1 t1 on t1.ID = t2.HomeAddressID
join (select id, max(somedatefield) from  table1 group by id) t3 on t3.id = t1.id
Where  t2.HomeAddress <> t1.address
like image 34
HLGEM Avatar answered Nov 15 '22 01:11

HLGEM