473,761 Members | 9,284 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trouble with Update syntax

I'm new to SQL and can't figure out how to update my table
(StoreItemStatu s) that contains the current status for items in each
store (STORE_KEY, ITEM_KEY, STATUS,...).
I get updated status info in a table (I'll call it NewInfo) that
has similar fields. NewInfo may contain multiple records for each
Store/Item, but I will just use the latest status. I'm not sure how
to update StoreItemStatus using each record of NewInfo. Any advice is
greatly appreciated

Thanks,
Paul
Jul 20 '05 #1
14 2518
You've said you want the "latest" status but you haven't told us how to
determine which the latest row is. I'll assume NewInfo has a DATETIME column
(status_dt) and that (store_key, item_key, status_dt) is unique.

UPDATE StoreItemStatus
SET status =
(SELECT status
FROM NewInfo AS N
WHERE store_key = StoreItemStatus .store_key
AND item_key = StoreItemStatus .item_key
AND status_dt =
(SELECT MAX(status_dt)
FROM NewInfo
WHERE store_key = N.store_key
AND item_key = N.item_key))

--
David Portas
SQL Server MVP
--
Jul 20 '05 #2
On Mon, 24 May 2004 07:08:14 +0100, David Portas wrote:
You've said you want the "latest" status but you haven't told us how to
determine which the latest row is. I'll assume NewInfo has a DATETIME column
(status_dt) and that (store_key, item_key, status_dt) is unique.

UPDATE StoreItemStatus
SET status =
(SELECT status
FROM NewInfo AS N
WHERE store_key = StoreItemStatus .store_key
AND item_key = StoreItemStatus .item_key
AND status_dt =
(SELECT MAX(status_dt)
FROM NewInfo
WHERE store_key = N.store_key
AND item_key = N.item_key))


Hi David,

Unless the OP is sure that every Store / Item combination has at least one
row in the NewInfo table, he'd better add

WHERE EXISTS
(SELECT *
FROM NewInfo
WHERE store_key = StoreItemStatus .store_key
AND item_key = StoreItemStatus .item_key)

to this query.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #3
Thank you! Your assumptions were correct, and I believe this will work.
Jul 20 '05 #4
> Unless the OP is sure that every Store / Item combination has at least one
row in the NewInfo table, he'd better add


Hugo,

The NewInfo table will only contain a small subset of the Store/Item
combinations ( < 1k).
The StoreItemStatus table has ~500k records. I was considering using
cursors to iterate through the NewInfo records and updating the
associated StoreItemStatus records.
Is this a bad idea?
Jul 20 '05 #5
> I was considering using
cursors to iterate through the NewInfo records and updating the
associated StoreItemStatus records.
Is this a bad idea?


Cursors are almost always a bad idea. Have you tried the WHERE EXISTS code
that Hugo posted?

--
David Portas
SQL Server MVP
--
Jul 20 '05 #6
"David Portas" <RE************ *************** *@acm.org> wrote in message news:<Kt******* *************@g iganews.com>...
I was considering using
cursors to iterate through the NewInfo records and updating the
associated StoreItemStatus records.
Is this a bad idea?


Cursors are almost always a bad idea. Have you tried the WHERE EXISTS code
that Hugo posted?


Yes, I did implement the WHERE EXISTS, along with the code you
supplied,
and with a few minor tweaks everything worked great.
I haven't worked much with any RDBMS and the cursors were an easier
concept for me to grasp than the multiple nested queries, which is why
I asked about them.
I've learned a lot working through this problem, and I really
appreciate your help.

Thanks again,
PB
Jul 20 '05 #7
bo*****@hotmail .com (bo*****@hotmai l.com) writes:
Yes, I did implement the WHERE EXISTS, along with the code you
supplied,
and with a few minor tweaks everything worked great.
I haven't worked much with any RDBMS and the cursors were an easier
concept for me to grasp than the multiple nested queries, which is why
I asked about them.
I've learned a lot working through this problem, and I really
appreciate your help.


If David's and Hugo's syntax was too contrived for you, here is
an alternative:

UPDATE StoreItemStatus
SET status = n.status
FROM StoreItemStatus s
JOIN NewInfo AS n ON n.store_key = s.store_key
AND n.item_key = s.item_key
JOIN (SELECT store_key, item_key, maxstatus = MAX(status_dt)
FROM NewInfo AS
GROUP BY store_key, item_key) AS nn
ON n.store_key = nn.store_key
AND n.item_key = nn.item_key
AND n.status_dt = nn.maxstatus

Except for the UPDATE SET part, this is how you would write a SELECT
statement to view the existing rows, and what the new values would be.

The thing in parenthesis is a derived table. Logically it is a temp
table in the middle of the query. However, SQL Server does not necessarily
materialize it, and may recast the computation order as long as the
result is the same.

One advantage of writing your UPDATE statements this way, is that you
don't easily do the same mistake as David did: by leaving on the
WHERE clause, he set the status to NULL for rows for which there are
no updates.

It should be said, however, that the above is a an extension to SQL,
which is available only in SQL Server, Sybase and Informix. David's
and Hugo's solution is ANSI-SQL, so it is likely to be more portable,
if that is an issue for you.

And while you still might find cursors easier to handled that SET-
based statments, beware of that the processing time for a cursor
can be several magnitudes slower. (And of the two ways of writing the
UPDATE statements, mine is likely to be faster than David's and Hugo's.)
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #8
In this case it appears that the proprietary UPDATE... FROM syntax is "safe"
because the OP has confirmed my assumption about the key. For the benefit of
the OP here's my own example of why MS's UPDATE...FROM syntax is so
incredibly BAD in my opinion and why I always try to avoid it.

CREATE TABLE Countries (countryname VARCHAR(20) PRIMARY KEY, capitalcity
VARCHAR(20) NULL)

CREATE TABLE Cities (cityname VARCHAR(20) NOT NULL, countryname VARCHAR(20)
NOT NULL REFERENCES Countries (countryname), CONSTRAINT PK_Cities PRIMARY
KEY (cityname, countryname))

INSERT INTO Countries (countryname) VALUES ('USA',NULL)
INSERT INTO Countries (countryname) VALUES ('UK',NULL)

INSERT INTO Cities VALUES ('Washington',' USA')
INSERT INTO Cities VALUES ('London','UK')
INSERT INTO Cities VALUES ('Manchester',' UK')

The MS-syntax makes it all too easy for the developer to slip-up by writing
ambiguous UPDATE...FROM statements where the JOIN criteria is not unique on
the right side of the join.

Try these two identical UPDATE statements with a small change to the primary
key in between.

UPDATE Countries
SET capitalcity = cityname
FROM Countries JOIN Cities /* evil UPDATE... FROM syntax */
ON Countries.count ryname = Cities.countryn ame

SELECT * FROM Countries

ALTER TABLE Cities DROP CONSTRAINT PK_Cities
ALTER TABLE Cities ADD CONSTRAINT PK_Cities PRIMARY KEY (countryname,
cityname)

UPDATE Countries
SET capitalcity = cityname
FROM Countries JOIN Cities /* don't do this! */
ON Countries.count ryname = Cities.countryn ame

SELECT * FROM Countries
I get this from the first SELECT statement:

countryname capitalcity
-------------------- --------------------
UK London
USA Washington

and this from the second:

countryname capitalcity
-------------------- --------------------
UK Manchester
USA Washington

(though these results aren't guaranteed - that's part of the problem).

Why did the result change? The physical implementation has affected the
meaning of the code, with serious, potentially disastrous consequences. How
can you even test your code if its results are subject to change due to the
vagaries of storage, indexing and cacheing?

With the ANSI syntax there is no ambiguity. The UPDATE statement compels the
programmer to design an unambiguous assignment subquery that returns no more
than a single value.

UPDATE Countries
SET capitalcity =
(SELECT MIN(cityname)
FROM Cities
WHERE Countries.count ryname = Cities.countryn ame)

At the very least this forces the developer to reconsider whether the UPDATE
statement makes logical sense.

--
David Portas
SQL Server MVP
--

Jul 20 '05 #9
Thank you for the education. I agree that that there is potential for
disaster if using the UPDATE...FROM syntax but it also appears much
easier to implement if updating multiple fields.
How do you handle this David? I am envisioning something like the
following:

UPDATE TargetTable
SET Field1 =
(SELECT...),
Field2 =
(SELECT...),
...

Where the UPDATE...FROM syntax (using Erland's example) might look
like this:

UPDATE StoreItemStatus
SET status = n.status, Field2 = n.Field2, Field3 = n.Field3, ...
FROM StoreItemStatus s
JOIN NewInfo AS n ON n.store_key = s.store_key
AND n.item_key = s.item_key
JOIN (SELECT store_key, item_key, maxstatus = MAX(status_dt)
FROM NewInfo AS
GROUP BY store_key, item_key) AS nn
ON n.store_key = nn.store_key
AND n.item_key = nn.item_key
AND n.status_dt = nn.maxstatus
Jul 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
248480
by: Dave | last post by:
I have 2 tables, one with names, and another with addresses, joined by their CIVICID number (unique to the ADDRESSINFO table) in Oracle. I need to update a field in the NAMEINFO table for a particular surname in a particular town. I can select the records fine with this syntax (testing in Oracle SQL* Plus) SELECT NAMEINFO.LASTNAME, NAMEINFO.FIRSTNAME, NAMEINFO.MIDDLENAME, NAMEINFO.GENDER, ADDRESSINFO.REGION FROM NAMEINFO, ADDRESSINFO...
2
2890
by: Fork | last post by:
Hi, I am trying to execute a script from the command line as follows; c:\program files\mysql\bin>mysql -u root newsman < servers3.mysql But this gives me the following error; ERROR 1064 at line 3: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax
17
5028
by: kalamos | last post by:
This statement fails update ded_temp a set a.balance = (select sum(b.ln_amt) from ded_temp b where a.cust_no = b.cust_no and a.ded_type_cd = b.ded_type_cd and a.chk_no = b.chk_no group by cust_no, ded_type_cd, chk_no)
6
19171
by: HeadScratcher | last post by:
I am trying to speed up my update statements by removing inner select statements. Example: update orders set shipname = (select contactName from customers where customerid = orders.customerID) I read some articles which said that I should be able to use an inner join on the update statement like the following:
3
3123
by: Jerry | last post by:
Well, here is some weirdness. First, I noticed that I have 2 Set keywords (silly me). so I removed the 2nd "Set" but still got a syntax error. Then I removed the Where clause, and now it works perfectly. Is this correct? Or am I just getting lucky? I'm not completely clear on the fundamentals here. I update the table in my dataset, then I update the table on the server through the dataAdapter. I think I have a handle on the...
7
2227
by: Gary Paris | last post by:
I have a bound datagrid on my windowsform. I have the following declarations in the global module of the project: Public eDS As DataSet Public eDA As OleDb.OleDbDataAdapter In the Load routine of the form, I have the following code Dim eDS As New DataSet
3
3695
by: Ciara9 | last post by:
I am having problems trying to update a field in a database using a field in a form. I currently have two fields, Today and Tomorrow in a table named Date. The Today field automatically defaults to the current date, and what I am trying to accomplish is if this date changes, then the second field, Tomorrow, will automatically become equivalant to the value of Today +1. Sounds simple enough, however I cannot get the table to update. I am able to...
1
3255
by: sibusiso | last post by:
HI Can Any one help I have extra field on a table like FDate, FYear, FMonth, FDay, FDatename I have a triger that I will update this field every time transaction hapened, this field must be updated to the curent date, year, month, date name I wrote something like.
5
13379
matheussousuke
by: matheussousuke | last post by:
Hello, I'm using tiny MCE plugin on my oscommerce and it is inserting my website URL when I use insert image function in the emails. The goal is: Make it send the email with the URL http://mghospedagem.com/images/controlpanel.jpg instead of http://mghospedagem.comhttp://mghospedagem.com/images/controlpanel.jpg As u see, there's the website URL before the image URL.
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10136
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9988
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9923
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9811
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8813
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3911
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.