How to build dropdown list with database? - sql

I have try to build dropdown list that bind with database. I found out some errors that i dont really found. Please help, here below is my codes.
strSQL = "SELECT distinct table1.DeptName FROM Table1 " & _
"FULL JOIN Table2 on table1.DeptName = Table2.deptname" & _
"FULL JOIN Table3 on Table1.deptname = table3.DeptName " & _
"Where table1.deptname is not null order by table1.deptname "
Common.OpenConn()
Common.execReader(strSQL, params, dt, Common.txn)
If dt.Rows.Count > 0 Then
DropDownListDept.DataSource = dt
DropDownListDept.DataTextField = "DeptName"
DropDownListDept.DataValueField = "DeptName"
DropDownListDept.DataBind()
DropDownListDept.Items.Insert(0, New ListItem("Select Department Name", "0"))
End If
error found
Invalid column name 'DeptNameFULL'.

Your error is in your sql statement... The database is looking for a field called "DeptNameFULL" and of course there isn't.
strSQL = "SELECT distinct table1.DeptName FROM Table1 " & _
"FULL JOIN Table2 on table1.DeptName = Table2.deptname" & _
"FULL JOIN Table3 on Table1.deptname = table3.DeptName " & _
"Where table1.deptname is not null order by table1.deptname "
On the second line - you need a space after "Table2.deptname" - so it should be Table2.deptname " instead.

Related

VBScript Excel ADO connection: Get value using column alias in SQL query

In following code, I can get the count from excel using
objTempRecordset.Fields.Item(0).Value
However, I want to use column name alias in SQL.
i.e.
sSQL = "Select Count(*) AS RecCount FROM [NELimits$] A WHERE A.Type = 'A' AND A.ID = " &Chr(39) & "R001" & Chr(39)
and I want to get the result using:
objTempRecordset.Fields.Item("RecCount").Value
I also tried objTempRecordset.Fields.Item("_Count(*)_").Value but no luck
Can someone please let me know how to use column name alias in this case?
Note: Excel has 2 columns
ID: with values such as "R001", "R002"
Type: with values such as "A","B","C"
Sample code:
sSQL = "Select Count(*) FROM [NELimits$] A WHERE A.Type = 'A' AND A.ID = " &Chr(39) & "R003" & Chr(39)
Sqlquery = sSQL
sFilePath = "C:\Temp\DataSheet.xlsx"
Dim objTempConnection : Set objTempConnection = CreateObject("ADODB.Connection")
Dim objTempRecordSet : Set objTempRecordSet = CreateObject("ADODB.Recordset")
Dim strPath
'Define constants for objTempRecordset
Const adOpenStatic=3
Const adLockOptimistic=3
Const adLockPessimistic=2
Const adCmdText = &H001
'Open connection
objTempConnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="& sFilePath &";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
objTempRecordset.ActiveConnection = objTempConnection
objTempRecordset.CursorType = adOpenStatic
objTempRecordset.LockType = adLockOptimistic
objTempRecordset.Open Sqlquery
If objTempRecordset.EOF Or objTempRecordset.BOF Then
msgbox "no record"
End If
msgbox "Record Count: "&objTempRecordset.RecordCount
msgbox "Value:" & objTempRecordset.Fields.Item(0).Value
With the ACE SQL engine (used here in querying workbook), original field names, column aliases, or table names with spaces, special characters (non-alphanumeric), or reserved words need to be wrapped in square brackets or backticks to properly escape them.
Spaces
sSQL = "Select Count(*) AS [Rec Count] FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
sSQL = "Select Count(*) AS `Rec Count` FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
Special Characters (e.g., hyphen and pound/hashtag sign)
sSQL = "Select Count(*) AS [Rec-Count] FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
sSQL = "Select Count(*) AS `Rec-Count` FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
sSQL = "Select Count(*) AS [Rec#] FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
sSQL = "Select Count(*) AS `Rec#` FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
Reserved words (e.g., Count)
sSQL = "Select Count(*) AS [Count] FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
sSQL = "Select Count(*) AS `Count` FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
Otherwise, any field name or column alias is legitimate in query and can be read in record set in following formats:
objTempRecordset.Fields.Item(0).Value ' BY INDEX IN ITEM '
objTempRecordset.Fields.Item("Rec Count").Value ' BY NAME IN ITEM '
objTempRecordset.Fields("Rec Count").Value ' BY NAME IN FIELD COLLECTION '
objTempRecordset![Rec Count].Value ' BY NAME (EXCLAMATION POINT QUALIFIER) '
Furthermore, missing column aliases are handled in a special manner with ACE:
Missing Alias on Query Expression (e.g., Count function aggregation)
sSQL = "Select Count(*) FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
Missing Alias on Duplicate Field
sSQL = "Select ID, ID FROM [NELimits$] A" _
& " WHERE A.Type = 'A' AND A.ID = 'R003'"
For above two missing aliases, the ACE engine creates a column alias usually starting at Expr1 (inside MS Access -the usual interface to the ACE Engine) or Expr1000 for ODBC connections and incrementing for all other unnamed expressions or unnamed duplicate field references.

MS ACCESS SQL Join Subquery

I have two tables: newparts, storedparts
I insert the parts of the newparts, which are not jet in the storedparts into the storedparts:
SQL_String = "INSERT INTO storedparts " & _
"SELECT newparts.* " & _
"FROM storedparts " & _
"RIGHT JOIN newparts ON (storedparts.identifier = newparts.identifier) AND (storedparts.timeStamp = newparts.timeStamp) " & _
"WHERE ((storedparts.AutoID) Is Null);"
This is working fine so far. Now the Problem: Table storedparts is getting so big that the programm is taking too Long for the join process. My solution: Just compare the newparts not to all parts of the storedparts, but just to parts that aren't older than 4 days... I tried a subquery like this, but i can't get it to run.
SQL_String = "INSERT INTO storedparts " & _
"SELECT newparts.* " & _
"FROM storedparts (WHERE storedparts.timestamp > Now() - 4) " & _
"RIGHT JOIN newparts ON (storedparts.identifier = newparts.identifier) AND (storedparts.timeStamp = newparts.timeStamp) " & _
"WHERE ((storedparts.AutoID) Is Null);"
Any help is appreciated.
This wouldn't be a problem if your tables have indexes.
CREATE INDEX ndx_sp_identifier ON storedparts (identifier);
CREATE INDEX ndx_np_identifier ON newparts (identifier);
Then I suggest you change your query to something like this as #jarlh pointed out.
INSERT INTO storedparts
SELECT newparts.*
FROM newparts
LEFT JOIN storedparts
ON newparts.identifier = storedparts.identifier
AND newparts.timeStamp = storedparts.timeStamp
WHERE storedparts.AutoID Is Null;
You could add the where clause after the join statements and see if it improves the performance of the query . Else Try this and see if it works
SQL_String = "INSERT INTO storedparts " & _
"SELECT newparts.* " & _
"FROM ( SELECT * FROM storedparts WHERE
storedparts.timestamp > DateAdd ( 'd', -4, Now()) )sparts" & _
"RIGHT JOIN newparts ON (sparts.identifier = newparts.identifier) AND
(sparts.timeStamp = newparts.timeStamp) " & _
"WHERE ((sparts.AutoID) Is Null);"

MS Access vba query where

Simple Question.
For example, i have a Customer that have 10 Orders and each order include 6-10 Items.
i want to create a vba query that will desplay all the items of a specific customer.
My query is:
x = CustomerNum
Query = "Select OrderNum from CustomerOrderT Where CustomerNum = " & x
Set result = CurrentDb.OpenRecordset(Query)
y = result!OrderNum
'(there is a lot of orders on y)
Query = "Select Product From OrderProducts Where OrderNum = " & y
Set result = CurrentDb.OpenRecordset(Query)
The problem is that i only see the Products of the first order and i cannot see the products of all the orders that i select on the first query.
Need some help to handke this situation.
Thank you very much.
You can just execute a single query for all orders:
x = CustomerNum
Query = " SELECT CustomerOrderT.CustomerNum, " & _
CustomerOrderT.OrderNum, " & _
" OrderProducts.Product " & _
" FROM CustomerOrderT INNER JOIN OrderProducts " & _
ON CustomerOrderT.OrderNum = OrderProducts.OrderNum " & _
" WHERE (((CustomerOrderT.CustomerNum)=" & x & ")) " & _
"ORDER BY CustomerOrderT.OrderNum, " & _
" OrderProducts.Product;"
And then loop over all the records, noting each change in OrderNum
But beware of building SQL like this if you don't control how variable CustomerNum is assigned, as you open yourself to SQL injection attacks.

Query syntax on a large inner-joined select query linked to a control giving runtime 3071 error message

I am getting Runtime error message 3071 on the following query stating that the query is too complex. I have created queries in the past which have seemed more complex than this one. I would like to understand what generates this message:
sql_get = "SELECT tblValueChain01.IDMacroProcesso, tblValueChain02.IDMicroProcesso02, tblValueChain03.ID, tblDependencies01.ID AS DependencyID, tblValueChain02.MicroProcesso02, tblValueChain01.MacroProcess, tblValueChain01.TeamLead, tblValueChain01.LastOrganisationDate, tblValueChain01.TempiIndeterminati, tblValueChain01.TempiDeterminati, tblValueChain01.Interinali, tblValueChain01.PartTime, tblValueChain01.DailyMinutesAverage AS Minutes01, tblValueChain01.DailyMinutesHigh AS Minutes01H, tblValueChain01.DailyMinutesLow AS Minutes01L, tblValueChain02.MicroProcesso02, " & _
"tblValueChain02.DailyMinutesAverage AS Minutes02, tblValueChain02.DailyMinutesHigh AS Minutes02H, tblValueChain02.DailyMinutesLow AS Minutes02L, tblValueChain03.MicroProcess, tblValueChain03.MinutesPerDay AS Minutes03, tblValueChain03.MinutesPerDayHigh AS Minutes03H, tblValueChain03.MinutesPerDayLow AS Minutes03L, tblDependencies01.FlowDescription, tblDependencies01.FlowType, tblTeamsDepartments.Department, tblTeams.Team, tblDependencies01.Precision, " & _
"tblDependencies01.ServiceDelivery , tblDependencies01.RiskReduction, tblDependencies01.CapacityCreation, tblDependencies01.TargetCapacityCreation, tblDependencies01.Feasibility, tblDependencies01.Timeframe, tblDependencies01.Priority, tblDependencies01.Note, tblDependencies01.RedundantControls, tblDependencies01.RedundantControlsNotes, tblDependencies01.RedundantControlsPotSolution, tblDependencies01.RedundantControlsNotesSymbol, tblDependencies01.RedundantControlsPotSolSymbol, tblDependencies01.RolesAndResponsibilities, tblDependencies01.RolesAndResponsibilitiesNotes, " & _
"tblDependencies01.RolesAndResponsibilitiesPotSolution , tblDependencies01.RolesResponNotesSymbol, tblDependencies01.RolesRespPotSolSymbol, tblDependencies01.SubstandardSvcs, tblDependencies01.SubstandardSvcsNotes, tblDependencies01.SubStandardSvcsPotSolution, tblDependencies01.SubStandardSvcsNotesSymbol, tblDependencies01.SubStandardSvcsPotSolSymbol, tblDependencies01.KnowledgeGaps, tblDependencies01.KnowledgeGapsNotes, tblDependencies01.KnowledgeGap, " & _
"PotSolution , tblDependencies01.KnowledgeGapsNotesSymbol, tblDependencies01.KnowledgeGapsPotSolSymbol, tblDependencies01.ExcessiveOversight, tblDependencies01.ExcessiveOversightNotes, tblDependencies01.ExcessiveOversightPotSolution, tblDependencies01.ExcessiveOversightNotesSymbol, tblDependencies01.ExcessiveOversightPotSolSymbol, tblDependencies01.UpstreamErrors, tblDependencies01.UpstreamErrorsNotes, tblDependencies01.UpstreamErrorsPotSolution, tblDependencies01.UpstreamErrorsNotesSymbol, tblDependencies01.UpstreamErrorsPotSolSymbol, tblDependencies01.DefectsRework, " & _
"tblDependencies01.DefectsReworkNotes , tblDependencies01.DefectsReworkPotSolution, tblDependencies01.DefectsReworkNotesSymbol, tblDependencies01.DefectsReworkPotSolSymbol, tblDependencies01.OverProduction, tblDependencies01.OverproductionNotes, tblDependencies01.OverproductionPotSolution, tblDependencies01.OverproductionNotesSymbol, tblDependencies01.OverproductionPotSolSymbol, tblDependencies01.MotionTransport, " & _
"tblDependencies01.MotionTransportNotes , tblDependencies01.MotionTransportPotSolution, tblDependencies01.MotionNotesSymbol, tblDependencies01.MotionSolSymbol, tblDependencies01.DowntimeWaiting, tblDependencies01.DowntimeWaitingNotes, tblDependencies01.DowntimeWaitingPotSolution, tblDependencies01.WaitDowntimeNotesSymbol, tblDependencies01.WaitDowntimeSolSymbol, tblDependencies01.ExcessiveHandoffs, tblDependencies01.ExcessiveHandoffNotes, tblDependencies01.ExcessiveHandoffPotSolution, " & _
"tblDependencies01.ExcessiveHandoffsSymbol , tblDependencies01.ExcessiveHandoffsPotSolSymbol, tblDependencies01.RCSLABreachInternal, tblDependencies01.RCSLABreachExternal, tblDependencies01.RCCorporatePolicyBreach, tblDependencies01.RCOperatingModelDiscrepancy, tblDependencies01.RRSLABreachInternal, tblDependencies01.RRSLABreachExternal, tblDependencies01.RRCorporatePolicyBreach, tblDependencies01.RROperatingModelDiscrepancy, tblDependencies01.SSSLABreachInternal, tblDependencies01.SSSLABreachExternal, tblDependencies01.SSCorporatePolicyBreach, " & _
"tblDependencies01.SSOperatingModelDiscrepancy , tblDependencies01.KGSLABreachInternal, tblDependencies01.KGSLABreachExternal, tblDependencies01.KGCorporatePolicyBreach, tblDependencies01.KGOperatingModelDiscrepancy, tblDependencies01.EOSLABreachInternal, tblDependencies01.EOSLABreachExternal, tblDependencies01.EOCorporatePolicyBreach, tblDependencies01.EOOperatingModelDiscrepancy, tblDependencies01.UESLABreachInternal, tblDependencies01.UESLABreachExternal, tblDependencies01.UECorporatePolicyBreach, tblDependencies01.UEOperatingModelDiscrepancy, tblDependencies01.DefSLABreachInternal, " & _
"tblDependencies01.DefSLABreachExternal , tblDependencies01.DefCorporatePolicyBreach, tblDependencies01.DefOperatingModelDiscrepancy, tblDependencies01.OPSLABreachInternal, tblDependencies01.OPSLABreachExternal, tblDependencies01.OPCorporatePolicyBreach, tblDependencies01.OPOperatingModelDiscrepancy, tblDependencies01.EHSLABreachInternal, tblDependencies01.EHSLABreachExternal, tblDependencies01.EHCorporatePolicyBreach, " & _
"tblDependencies01.EHOperatingModelDiscrepancy , tblDependencies01.DTSLABreachInternal, tblDependencies01.DTSLABreachExternal, tblDependencies01.DTCorporatePolicyBreach, tblDependencies01.DTOperatingModelDiscrepancy, tblDependencies01.ECSLABreachInternal, tblDependencies01.ECSLABreachExternal, tblDependencies01.ECCorporatePolicyBreach, tblDependencies01.ECOperatingModelDiscrepancy " & _
"FROM (tblTeamsDepartments INNER JOIN tblTeams ON tblTeamsDepartments.ID = tblTeams.Department) INNER JOIN (tblValueChain01 INNER JOIN ((tblValueChain03 INNER JOIN tblValueChain02 ON tblValueChain03.IDMacroProcess = tblValueChain02.IDMicroProcesso02) INNER JOIN tblDependencies01 ON tblValueChain03.ID = tblDependencies01.IDSubProcess) ON tblValueChain01.IDMacroProcesso = tblValueChain02.IDMacroProcesso01) ON tblTeams.ID = tblDependencies01.Group WHERE [tblDependencies01].[ID]= '" & ID & "'"
Form_frmValueChainDynamic01.Form.RecordSource = sql_get
Possible typo:
...
INNER JOIN tblValueChain02 ON tblValueChain03.IDMacroProcess = tblValueChain02.IDMicroProcesso02)`
...
...perhaps should be IDMacroProcesso (missing "o" at the end of this field)?
Is [tblDependencies01].[ID] a number field? If so, then in your WHERE clause you've used single quotes denoting you're expecting to match a string; so this:
WHERE [tblDependencies01].[ID]= '" & ID & "'"
...should be written like this, if ID is a number:
WHERE [tblDependencies01].[ID]=" & ID
You've referred to most fields in your SELECT clause using the tableName.fieldName convention except for PotSolution (this may not be an issue, but it's good to be consistent!)
Some more things to try if the above doesn't work: http://allenbrowne.com/subquery-02.html#QueryTooComplex

Syntax error in SQL query

I am having problems implementing this query in vb.net.
The error message that I am getting is with the "as" in the first line.
This is a local sql compact database 3.5
cmd.CommandText = "UPDATE player as a " &
"SET starter = 'TRUE' " &
"WHERE NOT EXISTS (SELECT '1' " &
"FROM player AS b " &
"WHERE(b.school = a.school) " &
"AND b.weight = a.weight " &
"AND b.skill > a.skill)"
cmd.ExecuteNonQuery()
Error message - http://i40.tinypic.com/34gms5z.png
cmd.CommandText = "UPDATE a " &
"SET starter = 'TRUE' " &
"FROM player a " &
"LEFT JOIN player b " &
"ON a.school = b.school " &
"AND a.weight = b.weight " &
"AND b.skill > a.skill " &
"WHERE b.school is NULL"
cmd.ExecuteNonQuery()
Error message - http://i40.tinypic.com/106kn86.png
Does this work?
UPDATE player
SET starter = 'TRUE'
WHERE NOT EXISTS
(
SELECT * FROM player b
WHERE b.school = player.school
AND b.weight = player.weight
AND b.skill > player.skill
)
Edited to add:
This will probably run faster if you create an index:
CREATE INDEX player_school_weight ON player (school, weight, skill)
I believe that you want this:
UPDATE pl
SET
starter = 'True'
FROM
[Player] pl
LEFT JOIN
[Player] pl2 ON (pl.[School] = pl2.[School])
AND
(pl.[Weight] = pl2.[Weight])
AND
(pl2.[Skill] > pl.[Skill])
WHERE pl2.[School] IS NULL