Syntax error in SQL query - sql

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

Related

Syntax error on multiple join statement

Hello, I'm getting a syntax error on this sql statement, can anyone advise thanks
String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
"FROM tblStudent LEFT JOIN tblSchool " +
"ON (tblStudent.schoolID = tblSchool.schoolID) " +
"LEFT JOIN tblAgents " +
"ON (tblStudent.agentID = tblAgents.agentID) " +
"WHERE tblStudent.StudentID='" + studentID + "'";
I was hoping that I could do multiple joins
But I am getting a syntax error.
For access, parenthesis with multiple joins means the following. If you have three joins, there are two left parenthesis after the from. The last join does not have a right parenthesis.
String sql = "Select tblStudent.*,tblSchool.*,tblAgents.* " +
"FROM (tblStudent LEFT JOIN tblSchool " +
"ON (tblStudent.schoolID = tblSchool.schoolID)) " +
"LEFT JOIN tblAgents " +
"ON (tblStudent.agentID = tblAgents.agentID) " +
"WHERE tblStudent.StudentID='" + studentID + "'";
Access SQL injection has been covered in other threads .
String sql = "Select
tblStudent.StudentID,tblStudent.studentFirstName,"+
tblStudent.studentLastName,tblSchool.schoolName," +
tblAgents.agentFirstName,tblAgents.agentLastName " +
"FROM (tblStudent LEFT JOIN tblSchool " +
"ON (tblStudent.schoolID = tblSchool.schoolID)) " +
"LEFT JOIN tblAgents " +
"ON (tblStudent.agentID = tblAgents.agentID) " +
"WHERE tblStudent.StudentID=#studentID";
I believe your final SQL should look like this:
SELECT tblStudent.*
,tblSchool.*
,tblAgents.*
FROM tblSchool
RIGHT JOIN (
tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID
) ON tblSchool.schoolID = tblStudent.schoolID
WHERE tblStudent.StudentID=111;
So, the VBA code for creating this SQL should be
Dim sql As String
sql = "SELECT tblStudent.* ,tblSchool.* ,tblAgents.* " & _
"FROM tblSchool RIGHT JOIN (" & _
"tblAgents RIGHT JOIN tblStudent ON tblAgents.agentID = tblStudent.agentID" & _
") ON tblSchool.schoolID = tblStudent.schoolID " & _
"WHERE tblStudent.StudentID=" & studentID
Here I assume that studentID is numeric field. Also I would recommend to do not use * for selecting the data from more than one table, otherwise column names may be unpredictable and as mentioned in comments, it will require additional resources, which won't be used.

How to build dropdown list with database?

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.

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

How to make stored procedure in if..End if condition

I am beginner at stored procedures. I tried the following stored procedure in IF...End If condition so how to make it ... I am confused.... so anyone create it
strSql = "SELECT count(*) " & _
" FROM hist_billgen_report r, hist_billgen_header h " & _
" WHERE r.invoice_number=h.invoice_number " & _
" and h.macnum = '" & l_macnum & "' " & _
" and r.rep_type = 1 " & _
" and r.rep_call_type = '" & line_type & "' " & _
" and h.billing_job_id = '" & arg_job & "' "
'Special code for data lines for Newcore
If gcompany = "NCW" Then
strSql += " and r.rep_number not in ( "
strSql += "select distinct a.mdn from order_wireless a where"
strSql += " a.id in"
strSql += " ("
strSql += " select c.serviceid from cust_charge_file b, service_charges c, main_company_utilities d"
strSql += " where(b.chg_main_index = c.chargeid)"
strSql += " and c.serviceid = a.id"
strSql += " and (b.chg_main_category_id = d.utilities_id and d.utilities_type = 'CS' and (utilities_desc_short like '%FDS1%' or utilities_desc_short like '%FDS2%' or utilities_desc_short like '%FDS3%' or utilities_desc_short like '%MBS1%' or utilities_desc_short like '%MBS2%' or utilities_desc_short like '%MBS3%' ) )"
strSql += " )"
strSql += " and a.accountnumber = '" & l_macnum & "' "
strSql += " )"
End If
Putting a query into a stored procedure doesn't necessarily always mean a performance increase. Depending on the data in your tables, this query could be quite slow due to the OR LIKES '%%' in it, but you could do something like this:
create procedure [dbo].[spname]
#l_macNum int -- note, you haven't given a lot of information, create all query parameters with appropriate types here
-- more parameters
#arg_job int -- same
AS
BEGIN
if (#company = 'NCW')
begin
SELECT count(*)
FROM hist_billgen_report r, hist_billgen_header h
WHERE r.invoice_number=h.invoice_number
and h.macnum = #l_macNum
-- etc
and r.rep_number not in (
-- etc
)
end
else
begin
SELECT count(*)
FROM hist_billgen_report r, hist_billgen_header h
WHERE r.invoice_number=h.invoice_number
and h.macnum = #l_macNum
-- etc
end
END
GO
note the If and else logic are completely separate queries, as you cannot do what I think you were hoping to do in a contiguous query, without using dynamic sql. there are certain caveats to this but given you're new to sql, going to stick with that
I used -- etc as place holders for your text, as I'm not going to provide the entire solution :P
If that doesn't make sense, let me know.

SQL decode on column4 but only when column5 is distinct

I need to change the sum(decode()) expressions that are like
SUM(Decode(vcon.WAGON_TYPE_CODE,'MS',1,0))
to something that counts rows with vcon.WAGON-TYPE-CODE = 'MS' but only when wag.ACI-TAG-NO is distinct.
So if two columns look like this
vcon.WAGON_TYPE_CODE wag.ACI_TAG_NO
MS HI1111
SS C99999
MS HI1111
MS HI7777
SS HI8888
MS HI6666
The expression needs to return the number 3 rather than 4 as SUM(Decode(vcon.WAGON_TYPE_CODE,'MS',1,0)) currently does.
Any suggestions?
querySELECT = "SELECT "
querySELECT = querySELECT & "trn.WID_DATE, "
querySELECT = querySELECT & "trn.MINE_CODE, "
querySELECT = querySELECT & "trn.TRAIN_CONTROL_ID, "
querySELECT = querySELECT & "trn.NUM_CARS as HBD_Car_Count, "
querySELECT = querySELECT & "SUM(Decode(vcon.WAGON_TYPE_CODE,'MS',1,0)) M_Series, "
querySELECT = querySELECT & "(SUM(Decode(vcon.WAGON_TYPE_CODE,'SS',1,0))-SUM(Decode(wag.ACI_TAG_NO,'HI0000',1,0))) S_Series, "
querySELECT = querySELECT & "SUM(Decode(vcon.WAGON_TYPE_CODE,'CS',1,0)) C_Series, "
querySELECT = querySELECT & "SUM(Decode(wag.ACI_TAG_NO,'HI0000',1,0)) as No_Tag, "
querySELECT = querySELECT & "(COUNT(1) - trn.NUM_CARS) DB_Mismatch "
queryFROM = "FROM widsys.consist con, widsys.train trn, widsys.wagon wag, widsys.v_consist_ore_detail vcon "
queryWHERE = "WHERE trn.TRAIN_RECORD_ID = con.TRAIN_RECORD_ID "
queryWHERE = queryWHERE & "AND con.WAGON_ID = wag.WAGON_ID "
queryWHERE = queryWHERE & "AND ((vcon.CONSIST_ID=con.CONSIST_ID) "
queryWHERE = queryWHERE & "AND trn.MINE_CODE In (" & mine & ") "
queryWHERE = queryWHERE & "AND (trn.DIRECTION='N') "
queryWHERE = queryWHERE & "AND (wag.ACI_TAG_TYPE In ('CONTROL','SLAVE','ORE')) "
queryWHERE = queryWHERE & "AND (trn.WID_DATE>={ts '" & startDate & "'} "
queryWHERE = queryWHERE & "AND trn.WID_DATE<={ts '" & endDate & "'})) "
queryGROUPBY = "GROUP BY trn.WID_DATE, trn.MINE_CODE, trn.TRAIN_CONTROL_ID, trn.NUM_CARS "
queryORDERBY = "ORDER BY trn.WID_DATE DESC"
I think the following should work (this count the distinct wag.ACI_TAG_NO only when vcon.WAGON_TYPE_CODE='MS') :
COUNT(DISTINCT Decode(vcon.WAGON_TYPE_CODE,'MS',wag.ACI_TAG_NO,NULL))
e-g:
SQL> WITH data AS (
2 SELECT 'MS' WAGON_TYPE_CODE, 'HI1111' ACI_TAG_NO FROM DUAL UNION ALL
3 SELECT 'SS', 'C99999' FROM DUAL UNION ALL
4 SELECT 'MS', 'HI1111' FROM DUAL UNION ALL
5 SELECT 'MS', 'HI7777' FROM DUAL UNION ALL
6 SELECT 'SS', 'HI8888' FROM DUAL UNION ALL
7 SELECT 'MS', 'HI6666' FROM DUAL
8 )
9 SELECT COUNT(DISTINCT decode(WAGON_TYPE_CODE,'MS',ACI_TAG_NO,NULL))
10 FROM DATA
11 ;
COUNT(DISTINCTDECODE(WAGON_TYP
------------------------------
3
Cheers,
--
Vincent
You could use a subquery that filters duplicate tags. Your query is pretty complex, but this would calculate just the sum you're looking for:
SELECT SUM(Decode(sub.WAGON_TYPE_CODE,'MS',1,0))
FROM (
SELECT DISTINCT vcon.WAGON_TYPE_CODE, wag.ACI_TAG_NO
FROM widsys.wagon wag
INNER JOIN widsys.consist con
ON con.wagon_id = wag.wagon_id
INNER JOIN widsys.v_consist_ore_detail vcon
ON vcon.CONSIST_ID = con.CONSIST_ID
) sub
The DISTINCT makes sure there is only one row per (wagon_type,aci_tag_no) combination.