SQL Join Query VB (Pretty Sumple, I'm just learning) - sql

I'm trying to make a query which has the same field in table A & table B. Then table B has the same field as table C. I want to left join all tables on table A. Is this possible? If yes, how close is my code to doing it?
Try
objConn = DBAccess.GetConnection
strBlder.Append("SELECT ")
strBlder.Append("FLD_NM, DATA_TYPE_CD, XML_PATH_TX, UPDT_USER_ID_NR, DOC_TMPL_FLD_ID_NR ")
strBlder.Append("FROM ")
strBlder.Append("LLC.[LLCW10_DCTMPFLD_TB] LEFT JOIN LLC.[DataMapTool_FieldMapping] ")
strBlder.Append("ON LLC.[LLCW10_DCTMPFLD_TB].DOC_TMPL_FLD_ID_NR = LLC.[DataMapTool_FieldMapping].DocumentTemplateFieldID ")
strBlder.Append("& LEFT JOIN LLC.[DataMapTool_FieldMapping] ")
strBlder.Append("ON LLC.[DataMapTool_FieldMapping].FieldMappingStatusID = LLC.[DataMapTool_FieldMappingStatus].FieldMappingStatusID ")
strBlder.Append("ORDER BY FLD_NM ;")
dsData = DBAccess.ExecuteDataTable(objConn, CommandType.Text, strBlder.ToString())
'execute non query - takes sp name

The error you are getting(after removing the &) is because LLC.[DataMapTool_FieldMapping] is repeated and thats a problem. Instead of your from clause try something like:
FROM (LLC.[LLCW10_DCTMPFLD_TB] LEFT JOIN LLC.[DataMapTool_FieldMapping] ON LLC.[LLCW10_DCTMPFLD_TB].DOC_TMPL_FLD_ID_NR = LLC.[DataMapTool_FieldMapping].DocumentTemplateFieldID)
LEFT JOIN LLC.[DataMapTool_FieldMappingStatus] ON LLC.[DataMapTool_FieldMappingStatus].FieldMappingStatusID = LLC.[DataMapTool_FieldMapping].FieldMappingStatusID
Note that the LLC.[DataMapTool_FieldMapping] is referenced in the first join and then only the .FieldMappingStatusID field is referenced in the second join. Your initial query would have been trying to add the same table to the query twice without giving it an alias which confuses the query analyzer.
Basically the new from clause will attach the first two tables together then attach the third table onto the result of the first join.

Looks good to me, but there is that strange & before the LEFT JOIN LLC.[DataMapTool_FieldMapping] ... take that out.

Related

Dynamic Selection Query with Criteria in Ms Access | SQL

I have a query in which I select multiple values. To create my form.
The results look like this :
the last Column [Candidat Nom] is a drop down list with an other query (lets call it Query 1) that select my drop down list values.
The selection is good and is what I'm looking for. Except I get the same value for all lines when they need to be different.
To simplify
let's take the following exemple
I have the following candidate that wants to join for the following job (Represented with their ID).
As we can see 2 candidates wants job N° 12. and 1 candidate for each other job.
What I get
All candidates are listed for every job.
What I want
What I actually did
is I put the following query (Query 1) on my column.
SELECT T_SALARIE.SALARIE_nom & " " & T_SALARIE.SALARIE_prenom AS Candidat Nom
FROM T_EMPLOI INNER JOIN (T_SALARIE INNER JOIN (T_SALARIE_EMPLOI LEFT JOIN T_STATUT_EMPLOI ON T_SALARIE_EMPLOI.SALARIE_EMPLOI_statut_id = T_STATUT_EMPLOI.STATUT_EMPLOI_id) ON T_SALARIE.SALARIE_NNI = T_SALARIE_EMPLOI.SALARIE_EMPLOI_salarie_nni) ON T_EMPLOI.EMPLOI_identifiant = T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant
WHERE (((T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*valid*" Or (T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*décidé*") AND ((T_EMPLOI.EMPLOI_entreprise_id)=1));
This gave me the result I want but with the issue I mentioned previously (Same result for each line)
So
I thought I needed a new Criteria.
I added one, where It's going to select the candidate when the two "emploi ID" of my actual table (Shown before) and the one helping me select the candidates are equal.
With the following query:
SELECT T_SALARIE.SALARIE_nom & " " & T_SALARIE.SALARIE_prenom AS Candidat, T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant
FROM T_EMPLOI INNER JOIN (T_SALARIE INNER JOIN (T_SALARIE_EMPLOI LEFT JOIN T_STATUT_EMPLOI ON T_SALARIE_EMPLOI.SALARIE_EMPLOI_statut_id = T_STATUT_EMPLOI.STATUT_EMPLOI_id) ON T_SALARIE.SALARIE_NNI = T_SALARIE_EMPLOI.SALARIE_EMPLOI_salarie_nni) ON T_EMPLOI.EMPLOI_identifiant = T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant
WHERE (((T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*valid*" Or (T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*décidé*") AND ((T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant)=[R_Select_COMOB]![ACTION_identifiant_emploi]));
But I keep on getting the following pop up that asks me to enter a Job ID
So how can I make the query for each line compare and select the right values?
I hope I was clear in explaining. If not please let me know so that I can add more details.
Thank you !
Thanks to your help and specially #June7 for his propositions, I found a solution regarding my problem :
I added a criteria to select values based on JobID that I wasn't selecting in the first hand.
And then based on the column (jobID) select the values needed
here is my final query :
SELECT
[SALARIE_nom] & " " & [SALARIE_prenom] & " (" & [SALARIE_NNI] & ")" AS Salarié, T_SALARIE_EMPLOI.SALARIE_EMPLOI_salarie_nni, T_SALARIE_EMPLOI.SALARIE_EMPLOI_id, T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant
FROM
(T_STATUT_EMPLOI INNER JOIN T_SALARIE_EMPLOI ON T_STATUT_EMPLOI.STATUT_EMPLOI_id = T_SALARIE_EMPLOI.SALARIE_EMPLOI_statut_id) LEFT JOIN R_Select_Salarie ON T_SALARIE_EMPLOI.SALARIE_EMPLOI_salarie_nni = R_Select_Salarie.SALARIE_NNI
WHERE
(((T_SALARIE_EMPLOI.SALARIE_EMPLOI_emploi_identifiant)=[Formulaires]![F_COMOB]![ACTION_identifiant_emploi]) AND ((T_STATUT_EMPLOI.STATUT_EMPLOI_statut) Like "*validé*") AND ((T_SALARIE_EMPLOI.SALARIE_EMPLOI_Entreprise) Like "*RTE*"));
And Then to update my values for each line. I added a VBA code that requery on input.
Private Sub ACTION_Candidats_P_Enter()
ACTION_Candidats_P.Requery
End Sub
With that my problem is solved.

How to query twice at once from one table with inner join SQL ASP.NET

I have two tables first table called TFile contains two columns: FromCity and ToCity.
They will have different values but from one column of the second table (TCity) and specifically from the column called CityName.Second table name TCity they have two column : IdCity AND CityName.
My problem I need to display data for two columns they got from second table FromCity and ToCity with inner join for two times.
I use this code to do that:
SqlCommand comm = new SqlCommand("select * from TFile " +
"inner join TCity AS A ON TFile.FromCity = A.IdCity " +
"inner join TCity AS B ON TFile.ToCity = B.IdCity " + " WHERE " + "TFile.Name", con);
Then display data to users as:
SqlDataReader srd = comm.ExecuteReader();
if (srd.HasRows)
{
while (srd.Read())
{
//FromCity
TextFrom.Text = srd["CityName"].ToString();
//ToCity
TextTo.Text = srd["CityName"].ToString();//=======================here problem
}
}
In the first line of the data display I can get the name of the city but if I repeat that in the second line it will just repeat the data. Here problem.I can't use a different name to access the second query instead of the field name CityName.This is the name of the field in the second table for which I display the names of the cities.
How can I access to data in this query:
"inner join TCity AS B ON TFile.ToCity = B.IdCity
So if I access to it then can display second data in this line:
TextTo.Text = srd["CityName"].ToString();
How can solve this problem ?
I bet you need to create field aliases to differentiate between values from the multiple joins on the same table. By the way, please make sure you protect yourself from "SQL injection" when using these types of queries. If you don't know what "SQL Injection" is then please take some time to look it up.
"select FromCityName=A.CityName, ToCityName=B.CityName, * from TFile "
And
//FromCity
TextFrom.Text = srd["FromCityName"].ToString();
//ToCity
TextTo.Text = srd["ToCityName"].ToString();//=======================here problem

ACCESS UPDATE OFF OF QUERY

UPDATE dbo_enrollment AS A INNER JOIN Get_New_PCP AS B
ON A.PartD_ID = B.PartD_ID SET A.Nbr = B.['UpdatePCP'];
So Get_New_PCP is a query I run to get all the changed values from the database with the latest import file.
The error I'm getting is that I Operation must use an updateable query...
Pretty familiar with SQL, and Access- I may have come across this issue before actually, is there any way to work around it without making a table out of the query results?
I thought it would act like a view...I tried to research it, but ACCESS UPDATE QUERY in my search just returns a bunch of update query syntax...
Any help would be much appreciated.
Thanks!
UPDATE
SELECT
c.MaxLoadDate,
a.CMS_Status_Update_Date,
a.Effective_Date,
a.PBP_Nbr,
a.Unique_Member_ID AS EnrolleeID,
a.First_Name+', '+a.Surname AS Enrollee,
a.Street_Address1, a.Street_Address2,
a.City,
a.State,
a.Zip,
a.Birth_Date AS DOB,
"(" & Left(d.[Phone],3) & ")" & Mid(d.[Phone],4,3) & "-" & Mid(d.[Phone],5,4) AS PCP_PhoneNumber,
a.HIN,
a.PartD_ID,
b.[Eff Date],
b.[PID] AS ['UpdatePCP'],
a.PCP_Nbr AS ['CurrentPCP'],
IIf(c.PartD_LIPSL Is Null,'W/o LIS','LIS') AS LISStatus
FROM ((dbo_enrollment AS a INNER JOIN cards_april2014 AS b
ON a.PartD_ID = b.RecNum)
LEFT JOIN
GetMaxDateForLISUpdate AS c ON a.HIN = c.HIN)
LEFT JOIN [CCAPM2] AS d
ON a.PCP_Nbr = d.PID
WHERE (((a.PCP_Nbr)<>b.[PID]) And ((a.CMS_Status)='Enrolled'))
DESC;
I'm guessing the GetMaxDateForLISUpdate query joined into Get_New_PCP query is the issue. Queries involving aggregates cannot be updated. Check here for options on working around this issue.

VB.NET LINQ to XML Left Join with ambiguous column name

I need to write a LINQ TO XML query, which queries two XML files exported from Access database tables. The original Access DB query looks like this:
SELECT
(
[TableB].[Code] Is Null,[TableA].[Code],
LCase(Left([TableA].[Code],1)) & ":" & [TableB].[code]
) AS Code,
Trim
(
[TableB].[Description] & " " & [TableA].[Description]
) AS Description
FROM TableA LEFT JOIN TableB
ON TableA.Code = TableB.SubProduct;
When I convert it to LINQ to XML, I have the problem of the right part of the left join is not available. My LINQ look like this:
Dim results = _
From a In TableA.Descendants("Product")
Group Join b In TableB.Descendants("Product")
On a.Element("Code").Value Equals b.Element("SubProduct").Value Into leftJoinGroup Group
From p In leftJoinGroup.DefaultIfEmpty
Select New With
{
I DON KNOW HOW TO WRITE IT
}
Both tables have the column named "Code". However, the variable TableB seems to be unavailable inside my Selectclause. I only have a and p available so I can't get the Code from TableB (b). How should I do that?
I just started using linq myself and ran into this issue last week. This was very helpful for me http://msdn.microsoft.com/en-us/vstudio/bb688088.aspx but here is an example of how to perform a left outer join in vb.net http://msdn.microsoft.com/en-us/vstudio/bb737909#lojoin.
In your example tableB is being stored into leftJoinGroup which your selecting from using p. To get values from tableB you will need to select from p and since your trying to concatenate the columns from both tableA and tableB, I would check if tableB record is null.
Dim results = From a In TableA.Descendants("Product") Group Join b In TableB.Descendants("Product") _
On a.Element("Code").Value Equals b.Element("SubProduct").Value Into leftJoinGroup = Group _
From p In leftJoinGroup.DefaultIfEmpty() _
Select New With { _
.Code = If(p Is Nothing, a.Element("Code").Value, String.Format("{0}:{1}", Left(a.Element("Code").Value.ToLower(), 1), p.Element("Code").Value)), _
.Description = If(p Is Nothing, a.Element("Description").Value, String.Format("{0} {1}", p.Element("Description").Value, a.Element("Description").Value))}
Here is an example of your code above, I didn't tested it. I've used this code when joining datatables not xdocuments. Sorry if this isn't clear this my first post here.

How do I test for DBNull so as not to crash with "Column .... does not belong to table row"?

I am reading 2 tables in T-SQL like so:
Select r.UID,c.Forename,c.Surname,c.DOB From c LEFT OUTER JOIN r on........
Then in VB.NET I loop through the dataset like so:
For Each drR In dsR.Tables(0).Rows......Next
However when I test like so:
If Convert.IsDBNull(drR("r.UID")) Then
Or
String.IsNullOrEmpty(drR("r.UID"))
Convert.IsDBNull(r.UID))
I crash with
Column 'UID' does not belong to table
row
when the second table r has no record.
I did try both r.UID and UID.
To recoup: All is fine when I have a record in the second table, but what must I do when I do not? How do I test for DBNull so as not to crash with "Column .... does not belong to table row"?
P.S. Regardng the 2 answers below: I have to test for UID so as to know whether there is a record in the 2nd table or not.
You need to do a few thing to get your code flying.
First consider side stepping your problem by using an INNER JOIN instead of the LEFT OUTER JOIN.
OR Split the problem and work with two sets.
A set with UIDs:
select r.Uid, c.Forename, c.Surname, c.DOB
from c
inner join r
on c.forename=r.forename and c.surname=r.surname
A set without UIDs:
select c.Forename, c.Surname, c.DOB
from c
left outer join r
on c.forename=r.forename and c.surname=r.surname
where r.Uid is null
But if you need to do it in one go with all the rows from the LEFT Table then you will need to check for DBNull and here is how to do that:
If Not IsDBNull(drR("UID")) Then
'Success
Debug.Print(drR("UID"))
Else
'Failure
End If
This is another way to do the same check:
If Not TypeOf drR("UID") Is DBNull Then
'Success
Debug.Print(drR("UID"))
Else
'Failure
End If
also if you are in a long tight loop you may gain performance by indexing the column:
Dim dt as DataTable = DAL.GetYourDataTable()
Dim ixUID As Integer = dt.Columns.IndexOf("UID")
For Each dr As DataRow In dt.Rows
If Not IsDBNull(dr(ixUID)) Then
'Success
Debug.Print(dr(ixUID))
Else
'Failure
End If
Next
change your query to:
Select isnull(r.UID,''),c.Forename,c.Surname,c.DOB From c LEFT OUTER JOIN r on
You could use the AS alias to specify the column name if needed combined with lvo's suggestion
SELECT ISNULL(r.UID,'') AS 'UID' ...etc...
In that way the column has a name and therefore would eliminate the test for checking the column name UID if it is present on another table.
Hope this helps,
Best regards,
Tom.
Put a break after the dataset is filled. Then in your watch window add the following to see what the column name is (assuming r.UID is the first column then columns(0) )
- i.e. columns(columnnumber - 1)
dsR.Tables(0).columns(0).ColumnName