"There is no row at position 0."
Hi I keep on getting this error message.
If mytable.Rows.Count >= 0 then
dim myid = dt.Rows(0).Item(6).ToString
End if
Please help me in this matter and I would never ever like to see this message again.Thanking you all.
qry_Sql = qry_Sql + " select SRNO,EMPNO,ATTN_YR,ATTN_MONTH,"
qry_Sql = qry_Sql + " GRP,TOT_HRS,MY_ID "
qry_Sql = qry_Sql + " from ATTD_HRS "
qry_Sql = qry_Sql + " ORDER BY EMP_NO "
If mytable.Rows.Count <= 0 Then
mygrp = dt.Rows(0).Item(5).ToString ---------------------
myid = dt.Rows(0).Item(6).ToString
End If
You should check to see if your table contains any rows...
If mytable.rows.Count > 0 then
If mytable.rows(0).items(2) >= 0 then
dim myid = dt.Rows(0).Item(6).ToString
End if
End if
Probably because mytable has no row at position 0, (rows(0) part).
You should check if there are rows/items before using them.
Related
I want to pull some stuff out of a database using a select query. I have the query i need already written in SQL Server management studio and it works. I tried just copy it in but it doesn't work. I have some other queries that do work and i tried to make it formatted like those, but it'll just see it as string since its between "" those things.
Below is the query, it uses the join function that doesn't appear to be recognized by vb.net. the query also uses certain tables from other parts of the database, those also dont seem to get recognized.
the query:
select th.Thickness, count(th.Thickness)
from dbname..trackinghistory th
join dbname..OrderDetailOptions odo on odo.odKey=th.odKey
join dbname..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo.[Group]=odo.optiongroup
and mpo.QuestionKey='KGLASS' and OptionType=5
where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' and th.StationID='HO4' and
left(odo.OptionCode,1) = 'H'
group by th.Thickness
I think i just need a push in the right direction, can someone here help me with how to properly format these type of queries?
my VB.Net code:
Sub SetButtonColor()
btnIsClicked = False
Dim iWeek As Integer = tbWeek.Text
Dim iYear As Integer = tbYear.Text
If sql.hasconnection And iWeek <> 0 Then
Dim dtimeStartDate As DateTime = GetWeekStartDate(tbWeek.Text, tbYear.Text) 'get the startdate from the textboxes week and year
Dim dtimeEndDate As DateTime = DateAdd(DateInterval.Day, 7, dtimeStartDate) 'add 7 days to the startdate to set the enddate
sql.runquery("SELECT th.Thickness, count(th.Thickness)" +
"from FVMASTER..trackinghistory th" +
"join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey" +
"join FVMASTER..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo.[Group]=odo.optiongroup and mpo.QuestionKey='KGLASS' and OptionType=5" +
"where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' and th.StationID='HO4' and left(odo.OptionCode,1) = 'H'" +
"group by th.Thickness")
If sql.sqldataset.Tables(0).Rows.Count > 0 Then
For Each row As DataRow In sql.sqldataset.Tables(0).Rows
Select Case row("Thickness")
Case 3
btn3.BackColor = Color.Red
Case 4
btn4.BackColor = Color.Red
Case 5
btn5.BackColor = Color.Red
Case 6
btn6.BackColor = Color.Red
Case 8
btn8.BackColor = Color.Red
Case 10
btn10.BackColor = Color.Red
Case 12
btn12.BackColor = Color.Red
Case 15
btn15.BackColor = Color.Red
Case 19
btn19.BackColor = Color.Red
Case 24
btn24.BackColor = Color.Red
End Select
Next
End If
end sub
i have for now just pasted in the query, i know that that wont work
The problem are the missing spaces in the SQL string. Just because the concatentated strings are on different lines, this does not add line breaks to the string.
E.g.,
"from FVMASTER..trackinghistory th" +
"join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey"
results in
"from FVMASTER..trackinghistory thjoin FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey"
As you can see, you get a thjoin in there, which should be th join.
Just write it as a single multiline string (which now includes the line breaks)
sql.runquery("SELECT th.Thickness, count(th.Thickness)
from FVMASTER..trackinghistory th
join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey
join FVMASTER..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo.[Group]=odo.optiongroup and mpo.QuestionKey='KGLASS' and OptionType=5
where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' and th.StationID='HO4' and left(odo.OptionCode,1) = 'H'
group by th.Thickness")
Alternatively, you can keep your original approach and add the missing spaces at the line end
sql.runquery("SELECT th.Thickness, count(th.Thickness) " +
"from FVMASTER..trackinghistory th " +
"join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey " +
"join FVMASTER..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo.[Group]=odo.optiongroup and mpo.QuestionKey='KGLASS' and OptionType=5 " +
"where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' and th.StationID='HO4' and left(odo.OptionCode,1) = 'H' " +
"group by th.Thickness")
I have an Excel file that contains some datas that I want to export into an Access db. In the C column I've got a field called 'Description'. Usually this field occupy just one cell, but it can happens that is more long.
In this case, for example, AP.01 has got 5 rows of description. How can update the first row with the next rows?
Public Sub updateDB(ByVal PathDB As String, str As String, id As Integer)
Dim db As New cDB
Dim v As New cVoce
Dim rs As ADODB.Recordset = db.RecordSet
v.Description = str
db.connetti_DB(PathDB)
db.get_rs("UPDATE Voice SET Description = '" + v.Description + "' WHERE id= '"+id+"'")
End Sub
Public Function get_rs(ByVal query As String) As ADODB.Recordset
If db Is Nothing Then rs = Nothing : Return rs
rs = New ADODB.Recordset
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
rs.LockType = ADODB.LockTypeEnum.adLockOptimistic
rs.Open(query, db)
Return rs
End Function
This code doesn't work because I update my current row, for this reason is useless the UPDATE instruction. How can I fix my code?
EDIT I post here the For loop
For r = 2 To grid.RowCount - 1
vett = Split(grid(r, 1).Text)
total = UBound(Split(grid(r, 1).Text, "."))
If grid(r, 1).Text <> "" Then
Select Case total
Case 0
Dim chapter As New cChapter
flag = 1
id = id + 1
chapter.Cod = grid(r, 1).Text.Substring(0, 1)
chapter.Description = grid(r, 3).Text
If Left(vett(0), 1) >= Chr(65) And Left(vett(0), 1) <= Chr(90) Then
chapter.Cod = Left(vett(0), 1)
oldChap = chap.Cod
If chapter.Cod <> oldCap Then
chapters.Add(chapter)
End If
End If
chapters.Add(chapter)
stringChap = chap.Description
Dim par As New cParagraph
If Left(vett(0), 2) >= Chr(65) And Left(vett(0), 2) <= Chr(90) Then
par.Cod = Left(vett(0), 2)
par.Cod_Chapter = Left(vett(0), 1)
oldPar = par.Cod
If par.Cod <> oldPar Then
paragraphs.Add(par)
End If
End If
If grid(r, 3).Text.Length > 255 Then
par.Description = grid(r, 3).Text.ToString.Substring(0, 252) + "..."
Else
par.Description = grid(r, 3).Text.ToString
End If
paragraphs.Add(par)
stringPar = par.Description
Case 1
flag = 2
id = id + 1
c_Voc = voc.Cod_Chapter
p_Voc = voc.Cod_Paragraph
voc.Cod_Chapter = grid(r, 1).Text.Substring(0, 1)
voc.Cod_Paragraph = grid(r, 1).Text.Split(".")(0)
voc.Cod_Voice = Right(vett(0), 2)
If grid(r, 3).Text.Length > 255 Then
voc.Description = grid(r, 3).Text.ToString.Substring(0, 252) + "..."
Else
voc.Description = grid(r, 3).Text.ToString
If voc.Description.EndsWith("-") Then
a = Replace(voc.Description, "-", "")
voc.Description = a
End If
End If
stringVoice = voc.Description
voices.Add(voc)
voices.Save_DB(dbDest)
Case 2
flag = 3
id = id + 1
sVoice = New cVoice
oldSvoice = voice.Cod_SVoice
sVoice.Cod_SVoice = Left(vett(0), 2)
If sVoice.Cod_SVoce <> oldSvoice Then
voices.Add(sVoice)
voices.Save_DB(dbDest)
End If
If grid(r, 3).Text.Length > 255 Then
sVoice.Description = grid(r, 3).Text.ToString.Substring(0, 252) + "..."
Else
sVoice.Description = grid(r, 3).Text
End If
stringSvoice = sVoice.Description
sVoice.Cod_Voce = Left(vett(0), 5)
sVoice.Price1 = grid(r, 12).Text
sVoice.Price2 = sVoice.Price1
sVoice.UniMi = grid(r, 11).Text
sVoce.Sep = "."
voices.Add(sVoce)
voices.Save_DB(dbDest)
End Select
Else
If flag = 1 Then
stringChap = grid(r, 3).Text
chap.Description = stringChap & grid(r, 3).Text
stringPar = grid(r, 3).Text
paragraph.Description = stringPar & grid(r, 3).Text
End If
If flag = 2 Then
stringVoice = grid(r, 3).Text
voc.Description = voc.Description & stringVoice
voices.updateDB(dbDest, stringVoice, id)
voices.Add(voc)
End If
If flag = 3 Then
stringSvoice = grid(r, 3).Text
sVoice.Description = stringSvoice & grid(r, 3).Text
voices.Add(sVoice)
End If
chapter.Save_DB(dbDest)
paragraph.Save_DB(dbDest)
voice.Save_DB(dbDest)
End If
Next
EDIT2 I declared id As Integer and when Code column has a value then id=id+1. In this way I always know which row I have to modify. I modified also updateDB (now I'm using 3 parameters) and I added a WHERE condition into my query. Despite the update, nothing has changed
In database you cannot store records without PrimaryKey (actually you can, but it is bad idea). Since in your solution id is in fact Excel row number (sorry if I'm not correct but it looks like from code) it could be very hard to maintain it in future (in case someone add or remove description row). It would be better to change id column to text and use code as PK.
Storing description then could be solved in 2 ways:
1) Concatenate all rows containing description into 1 variable adding vbNewLine in between and store it in description field.
2) More relational but also more complex - create 2nd table for description with PK as i.e. autonumber, ForeignKey Code referring to main table. Maintenance will be here very complex. Not really worth effort.
Amount of changes in code is quite big, so sorry I'll not provide fixed code but I hope idea is clear.
BTW: The reason why description is not updated is described in your post. You are increasing id only when code is present, so every description field from first group have id = 1. The most simple fix in your code would be to create 2 update statements - One for rows with code
UPDATE Voice SET Description = '" + v.Description + "' WHERE id= '"+id+"'
Second one for rows without code:
UPDATE Voice SET Description = Description + CHAR(13) + CHAR(10) + '" + v.Description + "' WHERE id= '"+id+"'
This code is supposed to create a graph of revenue from money made through sales tickets at an event.
The code only executes up to da.Fill(ds) when it returns the error, which can be seen at the end of the code.
Does anybody know why
Private Sub frmRevenue_Load(sender As Object, e As EventArgs) Handles Me.Load
frmMDI.addFormToCMS()
Dim dt As DataTable
dt = New DataTable
dt.Columns.Add("Fee")
Dim sales As Integer = 0
Dim gridtable As New DataTable
gridtable.Columns.Add("Month")
gridtable.Columns.Add("Total")
gridtable.Columns.Add("#")
For i = 1 To 12
sql = "SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = " & i & " AND (YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ") AND (Status = 'SOLD' OR RESERVED" _
& " = 'AWAITING CONFIRMATION' OR Status = 'AVAILABLE' OR Status = 'AWAITING PAYMENT');"
da = New OleDb.OleDbDataAdapter(sql, con)
ds = New DataSet
da.Fill(ds)
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
monthly(i) = monthly(i) + 1
contracts = sales + 1
total(i) = total(i) + dr.Item("Fee")
yearlytotal = yearlytotal + dr.Item("Fee")
Next
Next
For i = 1 To 12
Dim month As String
Select Case i
Case 1
month = "Jan"
Case 2
month = "Feb"
Case 3
month = "Mar"
Case 4
month = "Apr"
Case 5
month = "May"
Case 6
month = "Jun"
Case 7
month = "Jul"
Case 8
month = "Aug"
Case 9
month = "Sep"
Case 10
month = "Oct"
Case 11
month = "Nov"
Case 12
month = "Dec"
Case Else
month = "ERR"
End Select
gridtable.Rows.Add(month, FormatCurrency(total(i)), monthly(i))
Next
ugTickets.DataSource = gridtable
ugTickets.DisplayLayout.Bands(0).Columns("Month").Width = 35
ugTickets.DisplayLayout.Bands(0).Columns("#").Width = 20
ugTickets.DisplayLayout.Override.AllowUpdate = DefaultableBoolean.False
txtAnnual.ReadOnly = True
txtAnnual.BackColor = Color.White
txtAnnualContracts.ReadOnly = True
txtAnnualContracts.BackColor = Color.White
chRevenue.Titles("chTitle").Text = "Predicted revenue for " & Today.Year & " - " & Year(Today.AddYears(1))
txtAnnual.Text = FormatCurrency(yearlytotal, 2)
txtAnnualContracts.Text = contracts
chRevenue.Series("Series1").Name = "Revenue"
For i = 1 To 12
chRevenue.Series("Revenue").Points.AddY(total(i))
Next
Try
chRevenue.BackColor = Color.Transparent
chRevenue.Legends("Revenue").BackColor = Color.Transparent
chRevenue.Series("Revenue").ChartArea = "ChartArea1"
chRevenue.Series("Revenue").Color = Color.SkyBlue
chRevenue.Series("Revenue").ToolTip = FormatCurrency("#VALY", 2)
Catch
End Try
End Sub
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
The problem is with this bit of the SQL:
(YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ")
It should probably be
(YEAR(DatePurchased) = " & Today.Year & " OR YEAR(DatePurchased) = " & Year(Today.AddYears(1)) & ")
The OR in SQL (and in most other languages) needs to have two independently valid conditions on each side. The left hand side currently looks like this:
YEAR(DatePurchased) = 2016
...which is fine. But the right looks like this:
2017
...which isn't a valid boolean.
When you get an error like this on the da.Fill() line (ie. the line that's actually running the SQL in the database), the easiest way to debug it is to print out the value of the "sql" variable.
Often, you can just look at the SQL it's generated and the problem will be obvious. Other times you have to copy it and run it directly against your database to see what the problem is.
Might be your SQL, try:
"SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = '" & i &
"' AND (YEAR(DatePurchased) = '" & Today.Year &
"' OR '" & Year(Today.AddYears(1)) & "') " &
"AND (Status = 'SOLD' OR RESERVED = 'AWAITING CONFIRMATION' " &
"OR Status = 'AVAILABLE' " &
"OR Status = 'AWAITING PAYMENT');"
I have two tables in my database - MPRS and ALL_SSC. I want to update the ALL_SSC table with data from MPRS and in Access (where I test my SQL) it works.
However, when I run it in my VB 2010 program on the SQL Server database, it says table MPRS already exists.
I know it does! I'm not trying to create it. I'm updating FROM it... any ideas where this SQL is wrong?
SQL = "UPDATE ALL_SSC LEFT JOIN MPRS ON MPRS.MPAN = ALL_SSC.MPAN1 SET ALL_SSC.PC1 = Format([mprs].[pc],'00'), ALL_SSC.MSPCDC1 = Mid([mprs].[PC_EFD],7,4) & Mid([mprs].[PC_EFD],4,2) & Mid([mprs].[PC_EFD],1,2), ALL_SSC.MTSC1 = [mprs].[MTC], ALL_SSC.MSMCDC1 = Mid([mprs].[MTC_EFD],7,4) & Mid([mprs].[MTC_EFD],4,2) & Mid([mprs].[MTC_EFD],1,2), ALL_SSC.LLF1 = [mprs].[LLF], ALL_SSC.SUPPLIER1 = [mprs].[SUPPLIER], ALL_SSC.REGI1 = Mid([mprs].[SSD],7,4) & Mid([mprs].[SSD],4,2) & Mid([mprs].[SSD],1,2), ALL_SSC.ENG_STATUS1 = 0 WHERE (((ALL_SSC.MPAN1) Is Not Null) AND ([mprs].[ENERG_STATUS]='E'));"
cmd = New SqlCommand(sSQL, cNN)
Try
Try
If cNN.State <> ConnectionState.Open Then
cNN.Open()
End If
Catch exCnn As Exception
MsgBox(exCnn.Message)
End Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Cannot continue. " & ex.Message)
Exit Sub
End Try
You have accidentally used variable "sSQL" when you meant to use "SQL".
Yet another example of why meaningful variable names are important.
The correct syntax for a JOIN with UPDATE in SQL Server is:
UPDATE a
SET PC1 = . . .
FROM ALL_SSC a LEFT JOIN
MPRS m
ON m.MPAN = a.MPAN1
WHERE . . .;
That is, you need a FROM clause and it comes after the SET.
Thanks Gordon for your help. One or two other changes needed to move from Access SQL to SQL Server, but this is the SQL i ended up with working in SQL Server.
UPDATE a
SET
a.PC1 = '0' + m.[pc],
a.MSPCDC1 = substring(m.[PC_EFD],7,4) + substring(m.[PC_EFD],4,2) + substring(m.[PC_EFD],1,2),
a.MTSC1 = m.[MTC],
a.MSMCDC1 = substring(m.[MTC_EFD],7,4) +substring(m.[MTC_EFD],4,2) + substring(m.[MTC_EFD],1,2),
a.LLF1 = m.[LLF],
a.SUPPLIER1 = m.[SUPPLIER],
a.REGI1 = substring(m.[SSD],7,4) + substring(m.[SSD],4,2) + substring(m.[SSD],1,2),
a.ENG_STATUS1 = 0
FROM [myDataBase].[dbo].ALL_SSC a LEFT JOIN
[myDataBase].[dbo].MPRS m
ON m.MPAN = a.MPAN1
WHERE (((a.MPAN1) Is Not Null) AND (m.[ENERG_STATUS]='E'));
However, When I execute the exact same code on the database via VB 2010, I get the same failure message. This is the vb code
For iMPAN As Integer = 1 To 3
'mpan - energised
SQL = "UPDATE a SET a.PC" + iMPAN.ToString + " = '0' + m.[pc], a.MSPCDC" + iMPAN.ToString + " = substring(m.[PC_EFD],7,4) + substring(m.[PC_EFD],4,2) + substring(m.[PC_EFD],1,2), a.MTSC" + iMPAN.ToString + " = m.[MTC], a.MSMCDC" + iMPAN.ToString + " = substring(m.[MTC_EFD],7,4) +substring(m.[MTC_EFD],4,2) + substring(m.[MTC_EFD],1,2), a.LLF" + iMPAN.ToString + " = m.[LLF], a.SUPPLIER" + iMPAN.ToString + " = m.[SUPPLIER], a.REGI" + iMPAN.ToString + " = substring(m.[SSD],7,4) + substring(m.[SSD],4,2) + substring(m.[SSD],1,2), a.ENG_STATUS" + iMPAN.ToString + " = 0 FROM ALL_SSC a LEFT JOIN MPRS m ON m.MPAN = a.MPAN1 WHERE (((a.MPAN" + iMPAN.ToString + ") Is Not Null) AND (m.[ENERG_STATUS]='E'));"
Debug.Print(SQL)
cmd = New SqlCommand(sSQL, cNN)
Try
Try
If cNN.State <> ConnectionState.Open Then
cNN.Open()
End If
Catch exCnn As Exception
MsgBox(exCnn.Message)
End Try
cmd.ExecuteNonQuery()
Catch ex As Exception
Debug.Print(ex.Message)
MsgBox("Cannot continue. " & ex.Message)
Exit Sub
End Try
Next
I have following code:
Dim executedCmd As OleDb.OleDbCommand = m_dbMgr.GetCommand()
executedCmd.CommandText = "select * from [Parameters] where "
Dim SQLcondition As String = String.Empty
For i As Integer = 0 To ParameterName.Count - 1
executedCmd.CommandText += "ParameterName = #parametername" + i.ToString() + " and ParameterValue #ParamaterCondition" + i.ToString() + " #ParameterValue" + i.ToString()
executedCmd.Parameters.AddWithValue("#parametername" + i.ToString(), ParameterName(i))
executedCmd.Parameters.AddWithValue("#ParameterValue" + i.ToString(), ParameterValue(i))
executedCmd.Parameters.AddWithValue("#ParamaterCondition" + i.ToString(), Condition(i))
Next
ParameterName, ParameterValue, ParameterCondition all are same length ArrayList, but the code does not work properly. I have verified all the variables have values.
When I run the code it reports a syntax error: "missing operations in query expression"
The problem is that ParameterCondition has values like ('>', '<', '=',.... some logical SQL operators).
Edit: How can I include conditions in parameters?
Add 1 = 1 after where to simplify building logical expression. Notice that all conditions added by AND logical operator. You can generate parameter name from columns name.
executedCmd.CommandText = "select * from [Parameters] where 1 = 1"
....
executedCmd.CommandText += " AND " + ParameterName(i) + " " + Condition(i) + " #" + ParameterName(i)
executedCmd.Parameters.AddWithValue("#" + ParameterName(i), ParameterValue(i))
ParameterCondition must all be binary operators.
The database engine would check the syntax of the SQL statement before it replaces the parameters with values. So somethinhg like "WHERE #p1 #p2 #p3" will not be parsed correctly.
Replace your condition with a string-expression e.g.
commandtext = parameterName + condition + " #p1"