Invalid Column Name in SQL Server Management Studio - sql

When I execute this query in SQL Server Management Studio, this error appears:
'Msg 207, Level 16, State 1, Line 1
Invalid column name 'ACCOUNT_NO'.'
This is the code for the query:
DECLARE #largeaccnumber INT = ACCOUNT_NO
DECLARE #smallaccnumber INT
SET #smallaccnumber = (SELECT LEFT(#largeaccnumber, 6))
SELECT DNADRX.CODE,
DNADDR.NAME,
DNADDR.TYPE,
DNADDR.MAIL_NAME,
ADDRESS_LINE1,
ADDRESS_LINE2,
ADDRESS_LINE3,
TOWN_CITY,
COUNTY_STATE,
COUNTY_STATE_CODE,
COUNTRY,
POST_ZIP,
LAST_STAT_DATE,
ACCOUNT_NO
FROM DNADRX,
DNADDR,
BACCNT
WHERE DNADDR.CODE = DNADRX.ADDRESS_CODE
AND DNADDR.CODE = #smallaccnumber
ORDER BY DNADRX.CODE
I want the query to display the data from the columns of the different tables (the columns are listed in the SELECT bit of the query) from 3 different tables (DNADRX, DNADDR, BACCNT), and the factor linking all 3 tables together is the 6 digit code (ACCOUNT_NO in the BACCNT table, ADDRESS_CODE in the DNADRX table and CODE in the DNADDR table). Originally, ACCOUNT_NO from table BACCNT was 8 digits long, but I reduced it to the first 6 digits using SELECT LEFT and assigned this 6 digit value to the variable #smallaccnumber.
Whenever I try to execute the query, it keeps telling me that 'ACCOUNT_NO' is an invalid code name. I have checked the spelling, refreshed using IntelliSense and tried 'BACCNT.ACCOUNT_NO' instead of just 'ACCOUNT_NO' on the first line of the query but it still won't work (instead it says that the multi-part identifier could not be bound when I try 'BACCNT.ACCOUNT_NO').
I am really new to SQL coding so sorry if the answer to my problem is really simple.
Thank you for your assistance :)

You can try something like this.
This assumes you know the 6 character code. This query will only find results IF there is a record matching in EVERY table. If one table doesn't find a matching record this query will return NOTHING. If you want to find a row even if a recrod is missing from a table, replace the "INNER JOIN" with "LEFT OUTER JOIN"
SELECT Dnadrx.Code,
Dnaddr.Name,
Dnaddr.Type,
Dnaddr.Mail_Name,
Address_Line1,
Address_Line2,
Address_Line3,
Town_City,
County_State,
County_State_Code,
Country,
Post_Zip,
Last_Stat_Date,
Account_No
FROM Dnaddr
INNER JOIN BACCNT ON DNAADDR.CODE = BACCNT.ACCOUNT_NO
INNER JOIN Dnadrx ON Dnaaddr.Code=Dnaadrx.Address_Code
WHERE Dnaddr.Code='YOUR 6 CHARACTER CODE GOES HERE'
ORDER BY Dnadrx.Code;

Related

How to join 2 tables with multiple conditions each?

I have data split between 2 tables, and need to join the necessary data together for analysis.
One table Test 3 Output contains ID numbers, and the return value of the test. The other table Test Results contains the same IDs, along with their corresponding serial number and overall test result.
I need to combine these into a single table that just displays ID, serial number and test value.
Sorry in advance for the horrible SQL thats about to follow, I'm brand new to this.
I have 2 working queries that give me what I want, but I can't seem to join them together.
The first query:
select `ID`,`Serial Number` from `Test Results`t where (len(`Serial Number`)=16 and FailMode = '24V Supply FAIL')
This gets me the ID and serial number of all the tests that failed '24V supply'. It also filters out garbage serial numbers as the correct ones should have 16 digits.
The second query:
select `ID` from `Test 3 Output`o where o.`24V Supply (V)`<30
This gets me the ID and test results, and filters out some results that were greater than 30V. Note that '24V Supply(V) is the name of the column containing the test results.
Now when I try to join these with the ID, I get a syntax error. Here's what I tried:
select `ID`,`Serial Number`
from `Test Results`t
where (len(`Serial Number`)=16 and FailMode = '24V Supply FAIL')
left join (`Test 3 Output`o ON t.`ID` = o.`ID` where o.`24V Supply (V)`<30)
This gives the error:
Error: Syntax error (missing operator) in query expression (len(`Serial Number`)=16 and FailMode = '24V Supply FAIL') left join (`Test 3 Output`o ON t.`ID` = o.`ID` where o.`24V Supply (V)`<30)
I'm not sure what operator I'm missing but I had a feeling its related to the fact there's two where statements?
Can anyone offer some help?
Edit: I found a workaround since I can't use 2 where clauses with a join. I created 2 views with my 2 separate queries, and performed the join on those which got me what I wanted. I'd still like to hear a proper way of doing it though :)
You can join 2 subqueries like this:
SELECT q1.a, q1.b, q2.c
FROM (
(SELECT a, b FROM table1
WHERE b > 10) AS q1
LEFT JOIN
(SELECT a, c FROM table2
WHERE c > 20) AS q2
ON q1.a = q2.a
)
Doing the subqueries as separate query objects is easier to debug, but the query objects keep piling up...

How to fix Column does not exist on this Inner Join of two tables with three conditions?

Currently, I am trying to create a new table based on the Inner Join query of two tables with three conditions. However, the SQL Error window always tells me the columns does not exist even when they clearly do.
So this is what has to happen an Inner Join has to happen when two specific values are equal to each other in the table of the columns and where are third value shares a similarity.
This is because while the Plotletter in the first table is actually only one letter like for say A.
The Application could be written like ABCD.
I have already also tried to make the clear the fields are referred to the right table by following the suggestion, but the error still happens.
CREATE TABLE testschema.FinalPlantenpaspoort
AS
SELECT PrimaryIndex, jaarpr, proefcode, plotleter, plotcijfer, plot, X, Y
FROM testschema.plantenpaspoortsjabloon
JOIN testschema.weegschaalproeven
ON plantenpaspoortsjabloon.proefcode = weegschaalproeven.Intern_Proef_Nr
AND plantenpaspoortsjabloon.plotcijfer = weegschaalproeven.Objectnr
WHERE plantenpaspoortsjabloon.plotletter LIKE weegschaalproeven.Application
;
This the error and suggestion they give me but no luck.
ERROR: column weegschaalproeven.intern_proef_nr does not exist
LINE 5: ON plantenpaspoortsjabloon.proefcode = weegschaalproeven.Int...
^
HINT: Perhaps you meant to reference the column "weegschaalproeven.Intern_Proef_Nr".
SQL state: 42703
Character: 237
**
Edit 2/07/2019: PROBLEM HAS BEEN SOLVED BUT 0 RECORDS Selected.
**
Okay the problem seems to be solved but there is a new kind of problem while the code does works 0 records are selected because of the JOIN. And this should not be the case. I know there are records that matches because this a test where I made sure the tables of the shapefiles in QGIS contains data that is relevant.
Create TABLE testschema.finalplantenpaspoort AS
SELECT jaarpr, proefcodet, plotletter, plotcijfer, plot, X, Y
FROM testschema.plantenpaspoortsjabloon
JOIN testschema.weegschaalproeven
ON plantenpaspoortsjabloon.proefcodet = weegschaalproeven.intern_proef_nr AND plantenpaspoortsjabloon.plotcijfer = weegschaalproeven.objectnr
WHERE plantenpaspoortsjabloon.plotletter LIKE weegschaalproeven.application
;
**SELECT 0**
Query returned successfully in 72 msec.
I have found the sollution to my zero select problem, apparently I needed to set a special Like circumstance because otherwise the records could not be matched here it goes:
Create TABLE testschema.finalplantenpaspoort AS
SELECT proefcodet, proefnaam, datumvernietiging, oogstvernietigingsmethode, objectnr, productcode, potnummer, dosis, oppervlakte, eenheid, luikb, oogstbestemming, application, opmerking, proefjaar, proefcode, plotletter, plotcijfer, plot, X, Y
FROM testschema.plantenpaspoort
JOIN testschema.weegschaalproeven
ON plantenpaspoort.proefcode = weegschaalproeven.internproefnr AND plantenpaspoort.plotcijfer = weegschaalproeven.objectnr AND plantenpaspoort.plotletter LIKE ANY (regexp_split_to_array(weegschaalproeven.application , '\s*'))
;
GRANT ALL ON TABLE testschema.finalplantenpaspoort TO test_admin_test WITH GRANT OPTION;

SQL returns the unique identifier instead of the value in my Access UNON ALL SQL

So here is my project using MS Access 2010,
I have developed 2 queries to select 2 different reading periods. These queries are called CycleStart and CycleEnd. When I run these 2 queries individually I get expected output results. these 2 queries pull data from tables with a couple lookup fields in them. So the lookup fields use other tables where there are only 2 columns. The next step I use SQL to create a UNION ALL query to bring these 2 cycle queries together for reporting purposes. The problem I run into is that my resulting Union query does not output the same information as the 2 individual cycle queries.
Now the specific issues. My cycle queries have a couple lookup fields referencing another table. For example the Read_Cycle field comes for a table(Read_Cycles) and only has 2 columns, the unique identifer assigned by Access and the Read_Cycle column with the data I enter. When I run the cycle queries the field for Read_Cycle returns the Read_Cycle data as expected, but the union query does not. So here is some structure of my project:
Read_Cycles Table
|ID Col1 | |Cycle_ID Col2|
1 Spring
2 Fall
3 Winter
The data tables behind the CycleStart and the CycleEnd have fields that are lookup values referencing the above described Read_Cycles table.
Query CycleStart and CycleEnd return Spring or fall or winter, which ever value is associated with the record, correctly.
however, the problem I have is that the Union SQL Query returns the ID instead of the value, so instead of getting Fall, I get the 2.
Here is my UNION ALL SQL........
SELECT "CycleEnd" AS source,
[CycleEnd].[Recloser_SerialNo],
[CycleEnd].[Read_Date],
[CycleEnd].[3_Phase_Reading],
[CycleEnd].[A_Phase_Reading],
[CycleEnd].[B_Phase_Reading],
[CycleEnd].[C_Phase_Reading],
[CycleEnd].[Read_Cycle],
[CycleEnd].[PoleNo],
[CycleEnd].[Substation],
[CycleEnd].[Feeder],
[CycleEnd].[Feeder_Description],
[CycleEnd].[Recloser_Location]
FROM [CycleEnd]
UNION ALL
SELECT "CycleStart" AS source,
[CycleStart].[Recloser_SerialNo],
[CycleStart].[Read_Date],
[CycleStart].[3_Phase_Reading] * - 1,
[CycleStart].[A_Phase_Reading] * - 1,
[CycleStart].[B_Phase_Reading] * - 1,
[CycleStart].[C_Phase_Reading] * - 1,
[CycleStart].[Read_Cycle],
[CycleStart].[PoleNo],
[CycleStart].[Substation],
[CycleStart].[Feeder],
[CycleStart].[Feeder_Description],
[CycleStart].[Recloser_Location]
FROM [CycleStart];
All other fields are coming across just fine and as expected, I have narrowed it down to only fields that are a lookup in the original tables.
Any help would be greatly appreciated. Also my SQL experience is really limited so example code would help greatly.
UPDATE:
here is the sql from the CycleEnd that works. I got this by building the query then changing to the SQL view...
SELECT Recloser_Readings.Recloser_SerialNo,
Recloser_Readings.Read_Date,
Recloser_Readings.[3_Phase_Reading],
Recloser_Readings.A_Phase_Reading,
Recloser_Readings.B_Phase_Reading,
Recloser_Readings.C_Phase_Reading,
Recloser_Locations.PoleNo,
Recloser_Locations.Substation,
Recloser_Locations.Feeder,
Recloser_Locations.Feeder_Description,
Recloser_Locations.Recloser_Location,
Recloser_Readings.Read_Cycle
FROM (
Recloser_Inventory LEFT JOIN Recloser_Locations
ON Recloser_Inventory.PoleNo = Recloser_Locations.PoleNo
)
RIGHT JOIN Recloser_Readings
ON Recloser_Inventory.Serial_No = Recloser_Readings.Recloser_SerialNo
WHERE (((Recloser_Readings.Read_Cycle) = "8"));
UPDATE#2
I noticed I grabbed the wrong code that references the Read_Cycles table. Here it is...
SELECT Read_Cycles.Cycle_ID, Read_Cycles.ID
FROM Read_Cycles
ORDER BY Read_Cycles.Cycle_ID DESC;
UPDATE : SYNTAX ERROR FROM THE FOLLOWING CODE!!
SELECT "CycleEnd" as source,
[CycleEnd].[Recloser_SerialNo],
[CycleEnd].[Read_Date],
[CycleEnd].[3_Phase_Reading],
[CycleEnd].[A_Phase_Reading],
[CycleEnd].[B_Phase_Reading],
[CycleEnd].[C_Phase_Reading],
[CycleEnd].[Read_Cycle],
[CycleEnd].[PoleNo],
[CycleEnd].[Substation],
[CycleEnd].[Feeder],
[CycleEnd].[Feeder_Description],
[CycleEnd].[Recloser_Location]
FROM [CycleEnd] JOIN [Read_Cycles] ON [CycleEnd].[Read_Cycle] = [Read_Cycles].[ID]
UNION ALL SELECT "CycleStart" as source,
[CycleStart].[Recloser_SerialNo],
[CycleStart].[Read_Date],
[CycleStart].[3_Phase_Reading]*-1,
[CycleStart].[A_Phase_Reading]*-1,
[CycleStart].[B_Phase_Reading]*-1,
[CycleStart].[C_Phase_Reading]*-1,
[CycleStart].[Read_Cycle],
[CycleStart].[PoleNo],
[CycleStart].[Substation],
[CycleStart].[Feeder],
[CycleStart].[Feeder_Description],
[CycleStart].[Recloser_Location]
FROM [CycleStart] JOIN [Read_Cycles] ON [CycleStart].[Read_Cycle] = [Read_Cycles].[ID];

SQL - Getting a column from another table to join this query

I've got the code below which displays the location_id and total number of antisocial crimes but I would like to get the location_name from a different table called location_dim be output as well. I tried to find a way to UNION it but couldn't get it to work. Any ideas?
SELECT fk5_location_id , COUNT(fk3_crime_id) as TOTAL_ANTISOCIAL_CRIMES
from CRIME_FACT
WHERE fk1_time_id = 3 AND fk3_crime_id = 1
GROUP BY fk5_location_id;
You want to use join to lookup the location name. The query would probably look like this:
SELECT ld.location_name, COUNT(cf.fk3_crime_id) as TOTAL_ANTISOCIAL_CRIMES
from CRIME_FACT cf join
LOCATION_DIM ld
on cf.fk5_location_id = ld.location_id
WHERE cf.fk1_time_id = 3 AND cf.fk3_crime_id = 1
GROUP BY ld.location_name;
You need to put in the right column names for ld.location_name and ld.location_id.
you need to find a relationship between the two tables to link a location to crime. that way you could use a "join" and select the fields from each table you are interested in.
I suggest taking a step back and reading up on the fundamentals of relational databases. There are many good books out there which is the perfect place to start.

Data type mismatch while fetching data from one table into another

I'm trying to get data from a table CustomerCase of database TD_EDD; into a table CustomerCase of database DsVelocity. The problem is whenever I try to get the data, error message is generated because in CustomerCase table of TD_EDD database, there are 3 columns: LOB, ReferralSource and CaseType of type varchar; while in CustomerCase table of DsVelocity database, the 3 matching columns are LOBID, ReferralSourceID and CaseTypeID and are of type int.
I've simply tried to execute this query:
INSERT INTO [DsVelocity].[dbo].[CustomerCase]
([CustomerID]
,[Tier]
,[EscalationDate]
,[ReferralSourceID]
,[ICMSID]
,[LOBID]
,[TriggerRC]
,[TriggerAccount]
,[Project]
,[CaseTypeID]
,[DateDue]
,[SARFiledYes]
,[SARFiledNo]
,[TeamLead]
,[SARAmount]
,[InitialNotes]
,[WorkFlowStatus]
,[CaseDecision]
,[AccountsReviewed]
,[ActionDate]
,[SecondLvlReview]
,[CompanyType]
,[IfOther]
,[ClientType]
,[MergeFlag]
,[MergeCaseID]
,[AMLREP]
,[HighRiskYes]
,[HighRiskNo]
,[AutoCreated]
,[FileName]
,[SourceRefDate]
,[SourceRefID]
,[ETMAdd]
,[ETMRemove]
,[ETMDate]
,[Investigator]
,[InUseBy])
SELECT [CustomerID]
,[Tier]
,[EscalationDate]
,[ReferralSource]
,[ICMSID]
,[LOB]
,[TriggerRC#]
,[TriggerAccount]
,[Project]
,[CaseType]
,[DateDue]
,[SARFiledYes]
,[SARFiledNo]
,[TeamLead]
,[SARAmount]
,[InitialNotes]
,[WorkFlowStatus]
,[CaseDecision]
,[AccountsReviewed]
,[ActionDate]
,[2ndLvlReview]
,[CompanyType]
,[IfOther]
,[ClientType]
,[MergeFlag]
,[MergeCaseID]
,[AMLREP]
,[HighRiskYes]
,[HighRiskNo]
,[AutoCreated]
,[FileName]
,[SourceRefDate]
,[SourceRefID]
,[ETMAdd]
,[ETMRemove]
,[ETMDate]
,[Investigator]
,[InUseBy]
FROM [TD_EDD].[dbo].[CustomerCase]
and then ran into the following error:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'CRR' to data type int.
CRR is a data in the column ReferralSource.
Similar messages may appear in case of LOB and CaseType columns
The database server I'm using is MSSQL Server 2008 R2.
What is the solution to this problem???
EDIT-1: Tried using Inner Join with LOB, CaseType and ReferralSource tables. Now the error has disappeared, query ran ok, but I get data from only 2 rows. I can't understand why?????? I had more than 40 data in the [TD_EDD].[dbo].[CustomerCase] table, so all these data were supposed to be passed to the [DsVelocity].[dbo].[CustomerCase] table. What's wrong?
EDIT-2: Got it. CaseType column in [TD_EDD].[dbo].[CustomerCase] had mostly NULL values, only 2 rows had valid data. Hence, only 2 rows were sent to [DsVelocity].[dbo].[CustomerCase] becasue no corresponding ID match can be made for null values. I guess I figured it out myself. Thanks everyone.
You could try casting as already suggested or probably you're referring the wrong field name, like (I shall focus only on the one that has an error):
SELECT
,[ReferralSourceID]
,[LOBID]
,[CaseTypeID]
FROM [TD_EDD].[dbo].[CustomerCase]
Instead of ReferralSource use ReferralSourceID, instead of LOB use LOBID and instead of CaseType use CaseTypeID.
Or probably you need to reference the Reference Table on those fields like:
SELECT
,[ReferralSourceID]
,[LOBID]
,[CaseTypeID]
FROM [TD_EDD].[dbo].[CustomerCase] CC
INNER JOIN Referral R
ON CC.ReferralSource = R.ReferralSource
INNER JOIN LobTbl L
ON CC.LOB = L.LOB
INNER JOIN CaseTypeTbl C
ON CC.CaseType = C.CaseType
Try casting your varchar columns to int (assuming the data in your source columns is valid for int columns in target)
SELECT CAST(ReferralSource AS int),
CAST(LOB AS int),
CAST(CaseType AS int)
--etc