473,804 Members | 4,066 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inner Join Problem

The following query works fine in access and does exactly what I want
it to do however I get a syntax error when I port it over to SQL Server
2000.

-------------

UPDATE OrdersProducts INNER JOIN Products ON OrdersProducts. ProductID =
Products.Produc tID SET Products.Stock =
Products.Stock-OrdersProducts. Quantity
WHERE OrdersProducts. OrderID=63116

--------------

Any help would be greatly appreciated

Many thanks

Dec 14 '06 #1
12 3939
Hi,

I feel like my previous post failed... So here is what I was saying...
Just ignore it if my post reappears.;)

----------------------------------------------------------------------------------------------

You can't use the UPDATE statement this way...
Here is the complete definition of its syntax :
UPDATE
{
table_name WITH ( < table_hint_limi ted [ ...n ] )
| view_name
| rowset_function _limited
}
SET
{ column_name = { expression | DEFAULT | NULL }
| @variable = expression
| @variable = column = expression } [ ,...n ]

{ { [ FROM { < table_source } [ ,...n ] ]

[ WHERE
< search_conditio n ] }
|
[ WHERE CURRENT OF
{ { [ GLOBAL ] cursor_name } | cursor_variable _name }
] }
[ OPTION ( < query_hint [ ,...n ] ) ]
Thus, in your case, the correct syntax would be :
UPDATE Products
SET Products.Stock = Products.Stock - OrdersProducts. Quantity
FROM
Products
INNER JOIN OrdersProducts ON OrdersProducts. ProductID =
Products.Produc tID
WHERE
OrdersProducts. OrderID = 63116

----------------------------------------------------------------------------------------------

Enjoy,

Cédric Del Nibbio
MCP since 2003
MCAD .NET
MCTS SQL Server 2005
in**@bodykind.c om a écrit :
The following query works fine in access and does exactly what I want
it to do however I get a syntax error when I port it over to SQL Server
2000.

-------------

UPDATE OrdersProducts INNER JOIN Products ON OrdersProducts. ProductID =
Products.Produc tID SET Products.Stock =
Products.Stock-OrdersProducts. Quantity
WHERE OrdersProducts. OrderID=63116

--------------

Any help would be greatly appreciated

Many thanks
Dec 14 '06 #2
Hi,

you may not use the UPDATE statement this way...
UPDATE
{
table_name WITH ( < table_hint_limi ted [ ...n ] )
| view_name
| rowset_function _limited
}
SET
{ column_name = { expression | DEFAULT | NULL }
| @variable = expression
| @variable = column = expression } [ ,...n ]

{ { [ FROM { < table_source } [ ,...n ] ]

[ WHERE
< search_conditio n ] }
|
[ WHERE CURRENT OF
{ { [ GLOBAL ] cursor_name } | cursor_variable _name }
] }
[ OPTION ( < query_hint [ ,...n ] ) ]
In your case, the proper syntax would be :
UPDATE Products
SET Products.Stock = Products.Stock - OrdersProducts. Quantity
FROM
Products
INNER JOIN OrdersProducts ON OrdersProducts. ProductID =
Products.Produc tID
WHERE
OrdersProducts. OrderID = 63116

Enjoy.

Cédric Del Nibbio
MCP since 2003
MCAD .NET
MCTS SQL Server 2005
in**@bodykind.c om a écrit :
The following query works fine in access and does exactly what I want
it to do however I get a syntax error when I port it over to SQL Server
2000.

-------------

UPDATE OrdersProducts INNER JOIN Products ON OrdersProducts. ProductID =
Products.Produc tID SET Products.Stock =
Products.Stock-OrdersProducts. Quantity
WHERE OrdersProducts. OrderID=63116

--------------

Any help would be greatly appreciated

Many thanks
Dec 14 '06 #3
The ANSI SQL compliant rewrite of this query would be:

UPDATE Products
SET Stock = (
SELECT Products.Stock - OrdersProducts. Quantity
FROM OrdersProducts
WHERE OrdersProducts. ProductID = Products.Produc tID
AND OrdersProducts. OrderID=63116
)
WHERE EXISTS (
SELECT *
FROM OrdersProducts
WHERE OrdersProducts. ProductID = Products.Produc tID
AND OrdersProducts. OrderID=63116
)

Since this is standard SQL, it will run on any SQL Server installation,
and should run on any modern RDBMS. It might even run in MS Access.

HTH,
Gert-Jan
"in**@bodykind. com" wrote:
>
The following query works fine in access and does exactly what I want
it to do however I get a syntax error when I port it over to SQL Server
2000.

-------------

UPDATE OrdersProducts INNER JOIN Products ON OrdersProducts. ProductID =
Products.Produc tID SET Products.Stock =
Products.Stock-OrdersProducts. Quantity
WHERE OrdersProducts. OrderID=63116

--------------

Any help would be greatly appreciated

Many thanks
Dec 14 '06 #4
The following query appears to work correctly in SQL server, the only
problem (and it is a major problem) is that it sets the value of the
stock field to null on every record except the one that it is reducing.

Any ideas?

----------------------------------------------------------------------------------------------------
UPDATE Products

SET Products.Stock = Products.Stock -

(
select sum(OrdersProdu cts.Quantity)
from OrdersProducts
where ordersproducts. ProductID=produ cts.ProductID and
ordersproducts. orderid = 63116 group by ordersproducts. ProductID
)

FROM Products

----------------------------------------------------------------------------------------------------
Gert-Jan Strik wrote:
The ANSI SQL compliant rewrite of this query would be:

UPDATE Products
SET Stock = (
SELECT Products.Stock - OrdersProducts. Quantity
FROM OrdersProducts
WHERE OrdersProducts. ProductID = Products.Produc tID
AND OrdersProducts. OrderID=63116
)
WHERE EXISTS (
SELECT *
FROM OrdersProducts
WHERE OrdersProducts. ProductID = Products.Produc tID
AND OrdersProducts. OrderID=63116
)

Since this is standard SQL, it will run on any SQL Server installation,
and should run on any modern RDBMS. It might even run in MS Access.

HTH,
Gert-Jan
"in**@bodykind. com" wrote:

The following query works fine in access and does exactly what I want
it to do however I get a syntax error when I port it over to SQL Server
2000.

-------------

UPDATE OrdersProducts INNER JOIN Products ON OrdersProducts. ProductID =
Products.Produc tID SET Products.Stock =
Products.Stock-OrdersProducts. Quantity
WHERE OrdersProducts. OrderID=63116

--------------

Any help would be greatly appreciated

Many thanks
Dec 17 '06 #5
in**@bodykind.c om wrote:
The following query appears to work correctly in SQL server, the only
problem (and it is a major problem) is that it sets the value of the
stock field to null on every record except the one that it is reducing.

Any ideas?

----------------------------------------------------------------------------------------------------
Did you try the query that Gert-Jan posted?

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--

Dec 17 '06 #6
Yes, I tried his query and received the following error message: -

---------------------------------------------------------------------------------

Server: Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression.
The statement has been terminated.

---------------------------------------------------------------------------------

David Portas wrote:
in**@bodykind.c om wrote:
The following query appears to work correctly in SQL server, the only
problem (and it is a major problem) is that it sets the value of the
stock field to null on every record except the one that it is reducing.

Any ideas?

----------------------------------------------------------------------------------------------------

Did you try the query that Gert-Jan posted?

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--
Dec 17 '06 #7
in**@bodykind.c om wrote:
The following query appears to work correctly in SQL server, the only
problem (and it is a major problem) is that it sets the value of the
stock field to null on every record except the one that it is reducing.

Any ideas?

----------------------------------------------------------------------------------------------------
UPDATE Products

SET Products.Stock = Products.Stock -

(
select sum(OrdersProdu cts.Quantity)
from OrdersProducts
where ordersproducts. ProductID=produ cts.ProductID and
ordersproducts. orderid = 63116 group by ordersproducts. ProductID
)

FROM Products
Change
sum(OrdersProdu cts.Quantity)
to
coalesce(sum(Or dersProducts.Qu antity),0)

Alternatively, append the WHERE EXISTS portion of Gert-Jan's query.
Dec 17 '06 #8
>Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. <<

This tells you something very important about your data, namely that
your OrdersProducts or Products table or both have several occurences
of the same product_id in this order. Run the query by itself and find
the problem.

SELECT P.product_id
FROM OrdersProducts AS OP, Products AS P
WHERE OP.product_id = P.product_id
AND OP.order_id = 63116
GROUP BY P.product_id
HAVING COUNT(*) 1;

Since you did nopt post DDL, nobody can help any further. Oh, in case
some suggests using an UPDATE.. FROM.. syntax do not do it. That will
grab a random row from the subquery and use it -- totally scrambling
your database.

As a bit of education, you need to look up a good book on SQL to see
how the language really works. ACCESS is so far from SQL that it takes
a year to un-learn it; until then you are in danger writing SQL that
runs -- BUT not the way you meant it to.

I cleaned up your vague data element names and modified your original
ACCESS statement:

UPDATE (OrdersProducts AS OP
INNER JOIN
Products AS P
ON OP.product_id = P.product_id) AS Foobar
SET P.Stock = (P.stock_qty - OP.order_qty)
WHERE OP.order_id = 63116;

What a subquery expression in Standard SQL says is that we materialize
a working table, named Foobar in this example. If this syntax were
valid and consistent, then the UPDATE would apply to Foobar, not any of
the base tables!! Then the materialized table would disappear.
Nothing would have happened.

An UPDATE statement works on one and only one base table (or an
updatable VIEW that resolves to a single base table). If you could do
more than one table, then you would update the same rows multiple times
from the various JOINs.

Dec 17 '06 #9
in**@bodykind.c om (in**@bodykind. com) writes:
The following query appears to work correctly in SQL server, the only
problem (and it is a major problem) is that it sets the value of the
stock field to null on every record except the one that it is reducing.
That's rude.
--------------------------------------------------------------------------
--------------------------
UPDATE Products

SET Products.Stock = Products.Stock -

(
select sum(OrdersProdu cts.Quantity)
from OrdersProducts
where ordersproducts. ProductID=produ cts.ProductID and
ordersproducts. orderid = 63116 group by ordersproducts. ProductID
)

FROM Products
Since there is no WHERE clause to restrict the update, all rows are
updated.

It may work better if you attach Gert-Jan's WHERE clause:
> WHERE EXISTS (
SELECT *
FROM OrdersProducts
WHERE OrdersProducts. ProductID = Products.Produc tID
AND OrdersProducts. OrderID=63116
)
It's interesting that Gert-Jan's query failed with "Subquery returned more
than 1 value." That would indicate that your Access query is not correct
either. Then again, I don't know Access or Jet, so maybe it does what
you want to after all.

Here is is yet one more suggestion:

UPDATE Products
SET Stock = P.Stock - OP.Quantity
FROM Products P
JOIN (SELECT ProductID, Quantity = SUM(Quantity)
FROM OrderProducts
WHERE OrderID = 63116
GROUP BY ProductID) AS OP ON P.ProductID = OP.ProductID

This syntax is my personal preference, in terms of simplicity and under-
standability. It is also likely to be the best performancewise . But it
has the disctinct advantage that it only works on SQL Server, so if you
want a solution that works both on Access and SQL Server, this is not
for you.


--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Dec 17 '06 #10

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

Similar topics

3
6420
by: Prem | last post by:
Hi, I am having many problems with inner join. my first problem is : 1) I want to know the precedance while evaluating query with multiple joins. eg. select Employees.FirstName, Employees.LastName, TerritoryID, Employees.EmployeeID, RegionID, ProductID from Employees
8
6325
by: kieran | last post by:
Hi, I have the following sql statement. I originally had the statement with two INNER JOINS but in some situations was getting an error so changed the last INNER JOIN to a LEFT OUTER JOIN (as is seem below). This seemed to work but i am unsure why and would like to know in case it falls over again. Why did the two INNER JOINS not work, and am I correct to use the LEFT OUTER JOIN in this context. As you can see the table 'tblStaff1_2'...
5
4048
by: jason.evans | last post by:
Hi there. I am having an intrigueing problem. I have a query which left joins another query to itself twice. The original query is derived from a linked table in SQLServer 2000. When I run it on my pc It runs fine. However for other users in the office, it behaves as an inner join. ie it only returns the records fo which the join fields equal each other. This happens on every other pc
4
2486
by: algroth | last post by:
Hi! I try to do a nested inner join by sql, but I always get an "Syntax-error in FROM-clause". The statement I try around with is: SELECT * FROM st1 INNER JOIN st2 INNER JOIN st3
6
9320
by: dmonroe | last post by:
hi group -- Im having a nested inner join problem with an Access SQl statement/Query design. Im running the query from ASP and not usng the access interface at all. Here's the tables: tblEmployees empId -- EmpName -- EmpRole -- EmpManager -------....------------.... ---------....--------------- 1........ dan yella..........1..........2
52
6362
by: MP | last post by:
Hi trying to begin to learn database using vb6, ado/adox, mdb format, sql (not using access...just mdb format via ado) i need to group the values of multiple fields - get their possible variations(combination of fields), - then act on each group in some way ...eg ProcessRs (oRs as RecordSet)... the following query will get me the distinct groups
18
5044
by: Dave | last post by:
Guys I am really stuck on this one. Any help or suggestions would be appreciated. We have a large table which seemed to just hit some kind of threshold. They query is somewhat responsive when there are NO indexes on the table. However, when we index email the query takes forever. FACTS - The problem is very "data specific". I can not recreate the
3
2390
by: Anila | last post by:
Hi Friends, My problem with Inner join is ... first i joined two tables and i got the result. after that iam trying to join one more table its giving syn tax error in JOIN condition. Here is the Query
0
1285
by: stanlew | last post by:
Happy New Year everyone! I'm new to both T-SQL and this forum. I'm currently doing an internship and my first task was to create a small program which will send an email detailing the sales of the previous day versus monthly targets and sales. Most of the parts were figured out and eveything was done in Visual Studio. The gist of the code was written in one large chunk of SQL code, as below: SELECT derivedtbl_1.family AS 'Family',...
9
11922
by: shapper | last post by:
Hello, I am used to SQL but I am starting to use LINQ. How can I create Left, Right and Inner joins in LINQ? How to distinguish the different joins? Here is a great SQL example: http://www.codinghorror.com/blog/archives/000976.html
0
9710
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
9589
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10593
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
9163
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...
1
7626
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6858
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4304
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
3000
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.