Ambiguous Column Name 'plant' - sql

How to fix this error?. I've already tried looking for a double declaration of plant in my sql script, but there seems nothing wrong with my script. All other sql joins I made involving/having a column name ID work just fine anyway. Also when I try to run my original script which is this
select tblCustomerList.CustomerName, tblPackages.Package,tblChangeLevels.ChangeLevels,tblDevices.Devices,tblPlant.Plant
from ATPChangeControlBoard.tblCCB
inner join ATPChangeControlBoard.tblCustomerList
on ATPChangeControlBoard.tblCCB.custAffected=ATPChangeControlBoard.tblCustomerList.ID
inner join ATPChangeControlBoard.tblPackages
on ATPChangeControlBoard.tblCCB.packageAffected=ATPChangeControlBoard.tblPackages.ID
inner join ATPChangeControlBoard.tblChangeLevels
on ATPChangeControlBoard.tblCCB.changeLevel=ATPChangeControlBoard.tblChangeLevels.ID
inner join ATPChangeControlBoard.tblDevices
on ATPChangeControlBoard.tblCCB.devsAffected=ATPChangeControlBoard.tblDevices.ID
inner join ATPChangeControlBoard.tblPlant
on ATPChangeControlBoard.tblCCB.plant=ATPChangeControlBoard.tblPlant.ID;
it works just fine and doesn't show any error on the plant column.
Below is the image screenshot of the actual code I used that shows the error.
Pls. Help. TIA. :)

Just found the answer on another thread.
I change all the plant/[column name] declaration to tblPlant.plant/[tablename].[columnname] to directly differentiate between columns with the same column name.
In my case I change my code in the where clause from
and (#plant is null or plant= #plant)
to
and (#plant is null or tblPlant.plant= #plant)
although the other sql joins didn't require me to add extra code like this, this one did so I did so and just added extra code to the one that requires it.
I found the answer on a comment here, and since I can't upvote or comment yet, I just decided to emphasize here that it is what solved my problem. :)
Ambiguous column name error, how do I fix it?
by #JohnFx
he said that
"The problem is that you haven't specified the table name for the field "Flags" and it probably exists in more than one table in the query. Add the table name in the format "Tablename.flags" to the front of all references to fix the problem."

Related

Join query giving empty result SQL

SQL learner here, trying to make a join, but it seems to not work.
I have the following 2 tables:
#device_combined_players
#final_results2
The goal is to have a new table replacing the player_store_id from #final_results with the pseudo_name from #device_combined_players.
I have tried with:
SELECT #final_results2.player_store_id,
#device_combined_players.pseudo_name, #final_results2.genre FROM #device_combined_players INNER JOIN #final_results2 ON #final_results2.player_store_id = #device_combined_players.store_id
but I can't make it work, my output is simply an empty table.
Could you guys, please, give me some light? Thank you!
My expected result would be: as #final_results2 (image 2), but replacing player_store_id column by pseudo_name from #device_combined_players table.
EDIT: a screenshot with more details:
https://i.stack.imgur.com/lSyLb.png
And, I am answering myself, since I had 2 different issues here. Both are rookie mistakes, but I will leave them here so it helps somebody else in the future:
Take a look at the data type of your columns. They can cause conflicts if they are not the same as the columns you are referencing in a JOIN.
Check if your data doesn't have spaces. You can use TRIM and LEN to help you out answering this.
I sorted my problem like that.

Multiple Left Joins in the same query causes "Invalid Operation" Error

I have the following queries ...
Query #1
SELECT aa.DocNum, b.QualityClass
FROM dbo_TransferHistory AS aa LEFT JOIN PCQualityClass AS bb ON aa.DocNum = bb.DocumentNum
WHERE (((aa.DocNum)=[Enter Doc Num]));
Query #2
SELECT aa.DocNum, bb.QualityClass, cc.BldgCond
FROM (dbo_TransferHistory AS aa LEFT JOIN PCQualityClass AS bb ON aa.DocNum = bb.DocumentNum)
LEFT JOIN PCBldgCond AS cc ON aa.DocNum = cc.DocumentNum
WHERE (((aa.DocNum)=[Enter Doc Num]));
dbo_TransferHistory is an table I access through an ODBC connector.
PCQualityClass and PCBldgCond are two queries that are based off another ODBC table. Both of these queries have only the two respective fields referenced in the main query.
DocNum and DocumentNum are the same type ("Short Text" and a length of 12) and while I would like to make the names the same, I cannot.
When the query is run, an Inputbox pops up and [Enter Doc Num] is replaced with the Document Number I want the data for.
The queries were created in Access using the Create Query tool.
The problem is that while Query #1 will work, Query #2 causes the error "Invalid Operation".
Changing to inner joins will allow Query #2 to function but will cause issues as there are times that one or both of the two sub queries do not have data but I still need the data from the primary table.
Please help, I am at my wits end as to why this is not working. Is this an Access 2013 bug that will not allow for two Left Joins in the same query or something else I am missing?
The SQL looks like it should work, so the problem is probably the combination of the base queries plus the two left joins.
My general experience with Access queries on ODBC tables and with multiple outer joins is: even if you get them to work, they usually perform pretty badly.
So my suggestion is: Re-create the whole thing as view on SQL Server, and link that view. Then your Access query becomes something trivial like
SELECT * FROM dbo_ViewTransferHistory
WHERE DocNum=[Enter Doc Num]
Ok, so this is frustrating the absolute !##$% out of me. The syntax is correct and everything I see online says it should work. Out of pure frustration and some curiosity, I imported the ODBC tables into Access as local tables and changed the table references in the queries to use the local tables. OMG, now it works. Same data, same structure, different table type, and it !##$ing works. So it looks like the problem is in attempting to make multiple joins using ODBC. Unfortunately, I cannot create local tables from the ODBC every time this query gets run. Going to keep looking into this and see if I can find another workaround. Any other ideas?
Basically, Access will not allow multiple Outer Joins when using ODBC data sources. I am going to mark this as answered and rephrase the question in a new post.
Thank you.

ERROR in CREATE VIEW

I tried to create a new view in my MS Access database so I can select better from it but I wonder what's happening here.
CREATE VIEW new
AS
SELECT msthread.id,
msthread.threadname,
Count(msthread.threadname) AS TotalPost,
threadcategory
FROM msthread
LEFT OUTER JOIN msposts
ON msthread.threadname = msposts.threadname
GROUP BY msthread.id,
msthread.threadname,
msthread.threadcategory
Access gives me this error message when I try to execute that statement.
Syntax error in create table statement
Is there specific problems in creating view with JOINs? I'm trying to access 2 tables.
CREATE VIEW was introduced with Jet 4 in Access 2000. But you must execute the statement from ADO/OleDb. If executed from DAO, it triggers error 3290, "Syntax error in CREATE TABLE statement", which is more confusing than helpful.
Also CREATE VIEW can only create simple SELECT queries. Use CREATE PROCEDURE for any which CREATE VIEW can't handle.
But CREATE VIEW should handle yours. I used a string variable to hold the DDL statement below, and then executed it from CurrentProject.Connection in an Access session:
CurrentProject.Connection.Execute strSql
That worked because CurrentProject.Connection is an ADO object. If you will be doing this from outside Access, use an OleDb connection.
Notice I made a few changes to your query. Most were minor. But I think the query name change may be important. New is a reserved word so I chose qryNew instead. Reserved words as object names seem especially troublesome in queries run from ADO/OleDb.
CREATE VIEW qryNew
AS
SELECT
mst.id,
mst.threadname,
mst.threadcategory,
Count(mst.threadname) AS TotalPost
FROM
msthread AS mst
LEFT JOIN msposts AS msp
ON mst.threadname = msp.threadname
GROUP BY
mst.id,
mst.threadname,
mst.threadcategory;
Going out on a limb here without the error message but my assumption is that you need an alias in front of your non-aliased column.
You may also have a problem titling the view as new. This is a problem with using a generic name for a view or table. Try giving it a distinct name that matters. I'll use msThreadPosts as an example.
CREATE VIEW msThreadPosts
AS
SELECT msthread.id,
msthread.threadname,
Count(msthread.threadname) AS TotalPost,
msposts.threadcategory --Not sure if you want msposts or msthread just pick one
FROM msthread
LEFT OUTER JOIN msposts
ON msthread.threadname = msposts.threadname
GROUP BY msthread.id,
msthread.threadname,
msthread.threadcategory
As long as we are looking at this query lets fix some other things that are being done in a silly way.
Lets start off with aliasing. If you alias a column you can very easily make your query easy to understand and read to anyone who is inclined to read it.
CREATE VIEW msThreadPosts
AS
SELECT mt.id,
mt.threadname,
Count(mt.threadname) AS TotalPost,
mp.threadcategory
FROM mtas mt
LEFT OUTER JOIN msposts mp
ON mt.threadname = mp.threadname
GROUP BY mt.id,
mt.threadname,
mt.threadcategory
There now doesn't that look better.
The next thing to look as if your column names. msthread has an id column. That column name is incredibly generic. This can cause problems when a column isn't aliased and an id exists in mulitple places or there are muliple id columns. Now if we change that column name to msthreadID it makes things much clearer. The goal is to design your tables in a way that anyone working on your database can imidiatley tell what a column is doing.
The next thing to look at is your join. Why are you joining on thread name? threadname is likely a character string and therefore not terribly efficient for joins. if msthread as an id column and needs to be joined to msposts then shouldn't msposts also have that id column to match up on to make joins more efficient?

SQL Developer "disconnected from the rest of the join graph"

I have the following SQL:
select <misc things>
from pluspbillline
left outer join workorder
on workorder.siteid=pluspbillline.siteid
and workorder.wonum = pluspbillline.refwo
and workorder.orgid = pluspbillline.orgid
left outer join ticket
on ticket.ticketid = pluspbillline.ticketid
and ticket.class=pluspbillline.ticketclass
left outer join pluspsalesorder
on pluspsalesorder.salesordernum=pluspbillline.salesordernum
and pluspsalesorder.siteid=pluspbillline.siteid
In Oracle SQL Developer 4.0.0.13 (connected to a DB2 database), I get a squiggly line underneath the following italics: "from pluspbillline" and "left outer join workorder".
The warning says "pluspbillline is disconnected from the rest of the join graph". What does this mean?
I got this as well. I'm not exactly sure how to articulate it but the error seems to be based on the logical flow of the code.
Essentially because you mention the table pluspbillline before workorder I think it expects the join to be on pluspbillline.siteid=workorder.siteid etc.
It seems that the order of the conditions for joins should flow from the first identified tables to the latest ones. So the following should make it happy:
plusbillline to workorder on pluspbillline.siteid=workorder.siteid...
"" to ticket on pluspbillline.ticketid = ticket.ticketid...
"" to pluspsalesorder on pluspbillline.salesordernum = pluspsalesorder.salesordernum...
I don't believe this would change the work oracle does (assuming you don't use optimizer hints) so I'd only bother to change if you hate the squiggly lines.
I'm not sure what's causing Oracle SQL Developer to give the error. But I'm putting this comment here to format it properly.
A join graph might look something like this
pluspbillline ------+----< workorder
|
+----< ticket
|
+----< pluspsalesorder
The lines on the graph might be labeled with the join fields. But this gives you a basic idea.
I don't see any reason why you are getting this warning. A column name typo in your SQL perhaps? Or some quirk in Oracle's interface that it doesn't understand the DB2 metadata properly? I suggested trying IBM's tool to see if it's merely their program.
The issue is caused by the Oracle Procedure having the same named input parameter as the column on the table you are joining to.
i.e input parm named bank_nbr and a table BankDept.bank_nbr will cause the error if you have WHERE bank_nbr = BankDept.bank_nbr
I solved the issue by renaming the input parameter to in_bank_nbr and updating my where to read WHERE in_bank_nbr = BankDept.bank_nbr
I had the same message when hovering over the "LEFT" word, but the whole query ran without a problem. On the other hand, when I hovered over "WITH", I got a piece of advice about restructuring the whole query. So, that message about disconnection could be not a sign of an error, but a warning about a too complex sentence. SQLDeveloper's editor does not mention the level of the problem.

Using 'LIKE' against column names in a where clause

I started to take a look at the following question: https://stackoverflow.com/questions/8616458/sql-query-like-clarification
Unfortunately it appeared that the original question was somewhat unclear however I decided to interpret this as him trying to only run his query when certain columns in the schema matched his like condition. It's very possible that this wasn't what was being asked however I wanted to challenge myself to do this (posted as a new question since the original was unclear and likely to be deleted and very possible nothing related to this).
What I got to was the following:
select
[OrderID]
,[ProductID]
,[UnitPrice]
,[Quantity]
,[Discount]
from [Northwind].[dbo].[Order Details]
where
(
select top 1
COLUMN_NAME
from INFORMATION_SCHEMA.columns
where COLUMN_NAME like '%ProductID'
) like '%ProductID'
I'm aware how syntactically ridiculous this is however I put it here to give you an idea where my thought process was headed and was also hoping that based on this I could get feedback as to a better method of only running a query when there's a column in the database that matches a condition that you specify? I don't see any purpose for it anywhere - I'm just curious and think I could learn from this.
In SQL, column references must be fixed and known to be valid at the time the query is prepared. It's not legal for the column name to turn out to be invalid in hindsight, after the query begins executing.
The solution given by #Igor gets around this by running two queries, the first to test the system tables and then conditionally run the second. You can't do both in one query.
If I understand you correctly you can do it using system view sys.columns:
IF EXISTS (SELECT 1 FROM sys.columns WHERE name LIKE '%ProductID')
SELECT *
FROM [Northwind].[dbo].[Order Details]