Indexed Property error - sql

While debugging my code I found an inner exception which reads as:
In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.
In sql the script runs smoothly returning all the rows, but in vb it's not returning or finding any rows. I have checked that the primary key is in the table and defined. How can I fix this? I had a proir query which returned rows, but as soon as I added this new query the inner exception came.... I didn't change anything except the querystring.
This is what I've done:
Public Sub BindDeliveredItems()
Proir if statemets....
Else
queryString = "select distinct LS.[Route], LS.[SubRoute], LS.[Truck], Convert(VARCHAR(10), LS.[Date], 121) AS Date, LS.[DriverAssistantContract]" & _
",((del.CT*100 )/ todel.TCT) as Score" & _
"from [Warehouse].[dbo].[LoadSheet] LS" & _
"left join (select [Truck],[Date],[Status], count([Status]) CT from [Warehouse].[dbo].[LoadSheet]" & _
"WHERE status='Delivered'" & _
"group by [Truck],[Date],[Status]) Del" & _
"on LS.truck=Del.truck and LS.[Date]=del.[Date]" & _
"left join (select [Truck],[Date], count([Truck]) TCT from [Warehouse].[dbo].[LoadSheet]" & _
"group by [Truck],[Date]) todel" & _
"on LS.truck=toDel.truck and LS.[Date]=todel.[Date]" & _
"WHERE ls.[Date] = '2013-07-03'" & _
"AND ls.[Truck] = 'BX 39 LK GP'"
End If
Dim ds As DataSet = GetData(queryString)
If (ds.Tables.Count > 0) Then
gvDeliveredItems.DataSource = ds
gvDeliveredItems.PageSize = (10)
gvDeliveredItems.AllowPaging = True
gvDeliveredItems.DataBind()
End If
End Sub
Function GetData(ByVal queryString As String) As DataSet
Dim ds As New DataSet()
Try
Dim adapter As New SqlDataAdapter(queryString, SQLCon)
adapter.Fill(ds)
Catch ex As Exception
MessageBox(ex.Message)
End Try
Return ds
End Function
EDIT:
The first time the I can see the exception is on this line
Dim ds As DataSet = GetData(queryString)
And on this line the exception shows as well:
If (ds.Tables.Count > 0) Then
My previous sql string work perfect without changing anything. The only thing I changed was the querystring when it started to give me this exception

I'd suggest adding more whitespace into your query, e.g.:
queryString = "select distinct LS.[Route], LS.[SubRoute], LS.[Truck], Convert(VARCHAR(10), LS.[Date], 121) AS Date, LS.[DriverAssistantContract]" & vbCrLf & _
",((del.CT*100 )/ todel.TCT) as Score" & vbCrLf & _
"from [Warehouse].[dbo].[LoadSheet] LS" & vbCrLf & _
vbCrLf is a VB-ism. If you prefer, you could use Environment.NewLine
At the moment, there are no new lines or spaces inside the string from this string concatenation, so for example, those second and third lines join together as:
,((del.CT*100 )/ todel.TCT) as Scorefrom [Warehouse].[dbo].[LoadSheet] LS
Which isn't what you wanted, presumably.

Related

VB.net Checking if database exists before connecting to it

I found the following query in order to find out if a database table was created already or not:
if db_id('thedbName') is not null
--code mine :)
print 'db exists'
else
print 'nope'
Now I am wanting to use that same query within my VB.net application. This is the code I currently have elsewhere that connects to the database (that I am wanting to see if its there before doing all this):
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Initial Catalog=thedbName;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Of course the issue with this is that I have to know the database name first in order to connect to the database.
I then seem to be able to connect to the master database using this:
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
But that query seems to throw an error on Dim blah As String = cmd.ExecuteNonQuery() of:
Additional information: Incorrect syntax near ')'.
So I'm not all sure what I am missing in order to correct the issue with the query?
Need to know how to have the query come back and say 'exists' or 'nope'
Change Print() to Print (remove the parentheses.)
Better, don't use Print at all, use select.
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"select 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"select 'nope'"
Dim blah As String = CType(cmd.ExecuteScalar(), string)
ExecuteNonQuery returns the number of affected rows for updates and inserts. But what you are executing is a query.
ExecuteScalar returns the first column of the first row selected. The query above only returns one row with one value, so that's what it will return.
or do it like this
select * from sys.databases where [name] = 'thedbName'
if it returns a row, then the database exists, if not then it doesn't.
To check if a table exists within a database, use this
select * from sys.objects where [name] = 'theTableName' and type_desc = 'USER_TABLE'

OleDB Criteria Mismatch

This is my last working code. It saves data from a burst of string. Using , as a delimiter, I added them into an array. Even if it has null values, it saves nothing on the DB.
Dim query As String = "INSERT INTO tblGPSRoutes" & _
"(UTCTime,Status,Latitude,NSIndicator,Longitude,EWIndicator," & _
"SpeedOverGround,CourseOverGround,UTCDate,MagneticVariation,EWIndicatorB,Mode,Cheksum)" & _
" VALUES " & _
"(#utctime,#status," & _
"#lat,#nsindicator," & _
"#long,#ewindicator," & _
"#sog,#cog,#utcdate,#magnet," & _
"#ewindicatorb,#mode,#checksum)"
Using cmd As New OleDbCommand(query, con) 'myconnection - is your connection object'
With cmd.Parameters
.AddWithValue("#utctime", txt(1))
.AddWithValue("#status", txt(2))
.AddWithValue("#lat", txt(3))
.AddWithValue("#nsindicator", txt(4))
.AddWithValue("#long", txt(5))
.AddWithValue("#ewindicator", txt(6))
.AddWithValue("#sog", txt(7))
.AddWithValue("#cog", txt(8))
.AddWithValue("#utcdate", txt(9))
.AddWithValue("#magnet", txt(10))
.AddWithValue("#ewindicatorb", txt(11))
.AddWithValue("#mode", txt(12))
.AddWithValue("#checksum", txt(13))
End With
cmd.ExecuteNonQuery()
This is my edited code because I need to parse the latlon datas.. this is where the title appears.. can you see what's wrong?
Dim la As Double = Double.Parse(txt(3).Substring(0, 2)) + Double.Parse(txt(3).Substring(2)) / 60.0
Dim lo As Double = Double.Parse(txt(5).Substring(0, 3)) + Double.Parse(txt(5).Substring(3)) / 60.0
Dim query As String = "INSERT INTO tblGPSRoutes" & _
"(UTCTime,Status,Latitude,NSIndicator,Longitude,EWIndicator," & _
"SpeedOverGround,CourseOverGround,UTCDate)" & _
" VALUES " & _
"(#utctime,#status," & _
"#lat,#nsindicator," & _
"#long,#ewindicator," & _
"#sog,#cog,#utcdate)"
Using cmd As New OleDbCommand(query, con) 'myconnection - is your connection object'
With cmd.Parameters
.AddWithValue("#utctime", txt(1))
.AddWithValue("#status", txt(2))
If txt(3) IsNot Nothing Then
.AddWithValue("#lat", la)
Else
.AddWithValue("#lat", "No Data") 'is this possible?'
End If
.AddWithValue("#nsindicator", txt(4))
If txt(5) IsNot Nothing Then
.AddWithValue("#long", lo)
Else
.AddWithValue("#long", "No Data")
End If
.AddWithValue("#ewindicator", txt(6))
.AddWithValue("#sog", txt(7))
.AddWithValue("#cog", txt(8))
.AddWithValue("#utcdate", txt(9))
End With
cmd.ExecuteNonQuery() 'error here..
End Using
I was thinking that maybe because I removed the number of data's to be inserted on a pre-made access database throws it? As you can see, I cut off the number of fields in code2 because there had been some error on the strings sent to me, and they are not that important, so I removed the code where they will be inserted in the DB, though their fields are still there. That was my first assumption (but I think not really)
Anyway, I did not test it yesterday so I thought about it. My GPS module hardly get signals so I can't test thoroughly, (strings were from it, so if it does not work, so am I)

Select max visual studio 2010

I'm updating a program from Visual Basic 6 to Visual Studio 2010 and, of course, I have founded a lot of problems so solve.
I'm using Access database with four tables with the same Key (Indice).
If I use the code as follow, I can get the last record from CodDekafix Table:
Private Sub cmdLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLast.Click
Dim Con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\DEKAFIX\Consulta Dekafix\dekafix.mdb")
Dim cmd As New OleDbCommand()
Con.Open()
sql = "Select * From Indice Where CodDekafix=(Select max(CodDekafix) From Indice)"
But If I want to get all the results from all tables with the same Key (Indice) with the change as showed below the program doesn't work.
sql = "Select * from Indice, dekafix1, dekafix2, dekafix3" _
& " where CodDekafix=(Select max(CodDekafix) From Indice) and" _
& " Indice.CodDekafix = dekafix1.CodDekafix and" _
& " dekafix1.CodDekafix=dekafix2.CodDekafix and" _
& " dekafix2.CodDekafix=dekafix3.CodDekafix and" _
& " ORDER BY Indice.CodDekafix"
Your SQL code in the second code sample is invalid. When we strip out the formatting representing the string in VB code, you get this:
Select * from Indice, dekafix1, dekafix2, dekafix3
where CodDekafix=(Select max(CodDekafix) From Indice) and
Indice.CodDekafix = dekafix1.CodDekafix and
dekafix1.CodDekafix=dekafix2.CodDekafix and
dekafix2.CodDekafix=dekafix3.CodDekafix and
ORDER BY Indice.CodDekafix
You have two problems here:
1) There's an extra "and" before the ORDER BY clause. Remove it.
2) The first line of your WHERE clause has an ambiguous reference to
CodDekafix -- you need to specify what table that's coming from.
Replacing CodDekafix with Indice.CodDekafixshould do the trick.
sql = "Select * from Indice, dekafix1, dekafix2, dekafix3" _
& " where Indice.CodDekafix=(Select max(CodDekafix) From Indice) and" _
& " Indice.CodDekafix = dekafix1.CodDekafix and" _
& " dekafix1.CodDekafix=dekafix2.CodDekafix and" _
& " dekafix2.CodDekafix=dekafix3.CodDekafix" _
& " ORDER BY Indice.CodDekafix"

Unable to fill dataset with oracledataadpter

i am facing very strange problem , I am using the following piece of code but ds is not filled some times there is data in the ds but not always, I have change the connection pool and also restart the iis but no luck at all , I am not able to find where the problem is please help me out.
I am running the same query in the TOAD and its giving result , I have also commit the transaction for if any thing in inconsistent.
Dim command As New OracleCommand
Dim ds As New DataSet
Try
Using connection As New OracleConnection
(ConfigurationManager.ConnectionStrings("CA").ConnectionString.ToString())
connection.Open()
command.Connection = connection
command.CommandText = "SELECT w.portfolio, w.appl_group,
tm.trng_title, p.tt_program_title," & _
" p.created_date,
p.tt_target_completion_date, p.tt_prog_status," & _
" w.emp_id, w.first_name || ' ' ||
w.last_name, ('Y') training_done_flag," & _
" t.actual_completion_date,
p.created_by, w.people_manager, " & _
" w.project_manager, w.flag" &
_
" FROM tt_training_done_records t," & _
" wsr_employee w, " & _
" tt_training_master tm, " & _
" tt_newprogram p" & _
" WHERE(w.emp_id = t.employee_id)" & _
" AND t.training_info_id = tm.trng_id"
& _
" AND p.tt_program_id(+) =
t.program_id" & _
" AND tm.trng_id IN ( 'TT_009' ) " & _
" AND t.actual_completion_date BETWEEN
TO_DATE('11-Mar-2009') AND TO_DATE('11-Mar-2013') " & _
" "
Dim adpt As New OracleDataAdapter(command)
adpt.AcceptChangesDuringFill = False
adpt.Fill(ds)
connection.Close()
End Using
Don't rely on the default behavior of casting a string into a date. Either use a date literal or provide the format string argument. This introduces a dependency on NLS environment settings your .NET code should not depend upon.
Instead of TO_DATE('11-Mar-2013')
Try date '2013-03-11' or TO_DATE('11-Mar-2013'), 'DD-Mon-YYYY')

VBA string length problem

I have an Access application where everytime a user enters the application, it makes a temp table for that user called 'their windows login name'_Temp. In one of my reports I need to query using that table, and I can't just make a query and set it as the recourdsource of the report, since the name of the table is always different.
What I tried then was to programatically set the recordset of the report by running the query and setting the form's recordset as the query's recordset. When I tried this, it kept giving me an error about the query.
I tried to debug, and I found that the string variable isn't able to contain the whole query at once. When I ran it with break points and added a watch for the string variable, it shows me that it cuts off the query somewhere in the middle.
I've experienced this problem before, but that was with an UPDATE query. Then, I just split it into two queries and ran both of them separately. This one is a SELECT query, and there's no way I can split it. Please help!
Thank you
Heres what I've tried doing:
ReturnUserName is a function in a module that returns just the login id of the user
Private Sub Report_Open(Cancel As Integer)
Dim strQuery As String
Dim user As String
user = ReturnUserName
strQuery = "SELECT " & user & "_Temp.EmpNumber, [FName] & ' ' & [LName] AS [Employee Name], " & _
"CourseName, DateCompleted, tblEmp_SuperAdmin.[Cost Centre] " & _
"FROM (tblCourse INNER JOIN (" & user & "_Temp INNER JOIN tblEmpCourses ON " & _
user & "_Temp.EmpNumber = EmpNo) ON tblCourse.CourseID = tblEmpCourses.CourseID) " & _
"INNER JOIN tblEmp_SuperAdmin ON " & user & "_Temp.EmpNumber = tblEmp_SuperAdmin.EmpNumber" & _
"WHERE (((" & user & "_Temp.EmpNumber) = [Forms]![Reports]![txtEmpID].[Text])) " & _
"ORDER BY CourseName;"
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
Dim rsCmd As ADODB.Command
Set rsCmd = New ADODB.Command
rsCmd.ActiveConnection = CurrentProject.Connection
rsCmd.CommandText = strQuery
rs.Open rsCmd
Me.Recordset = rs
rs.Close
End Sub
This what strQuery contains when I add a breakpoint on rsCmd.CommandText = strQuery:
SELECT myusername_Temp.EmpNumber, [FName]
& ' ' & [LName] AS [Employee Name],
CourseName, DateCompleted,
tblEmp_SuperAdmin.[Cost Centre] FROM
(tblCourse INNER JOIN (myusername_Temp
INNER JOIN tblEmpCourses ON
myusername_Temp.EmpNumber = EmpNo) ON
tblCourse.CourseID=
(It's all one line, but I've written it like this because the underscores italicize the text)
And the error I get says Run Time Error: Join not Supported.
Not quite what I was hoping for, but guessing, for:
strQuery = "long query goes here"
Try:
strQuery = "some long query goes here "
strQuery = strQuery & "more query goes here "
BASED ON NEW INFORMATION:
strQuery = "SELECT " & user & "_Temp.EmpNumber, [FName] & ' ' & [LName] AS [Employee Name], " & _
"CourseName, DateCompleted, tblEmp_SuperAdmin.[Cost Centre] " & _
"FROM (tblCourse " & _
"INNER JOIN tblEmpCourses ON tblCourse.CourseID = tblEmpCourses.CourseID) " & _
"INNER JOIN (Temp INNER JOIN tblEmp_SuperAdmin " & _
"ON Temp.EmpNumber = tblEmp_SuperAdmin.EmpNumber) " & _
"ON Temp.EmpNumber = tblEmpCourses.EmpNo " & _
"WHERE " & user & "_Temp.EmpNumber = " & [Forms]![Reports]![txtEmpID] & _
" ORDER BY CourseName;"
Note that in VBA:
& [Forms]![Reports]![txtEmpID].[Text] &
That is, the reference to the form must go outside the quotes so you get the value.
NEW INFORMATION #2
Your best bet would be to add these tables to the Access query design window and create the joins that you want, then switch to SQL view and use the string generated for you. I do not believe that the string is too long, only that the SQL is incorrect. The SQL I posted above should work, but it may not be what you want.
You can programmatically create a querydef that fits the user. So, when your report is called, you
Delete LoginName_Query_Temp (CurrentDb.QueryDefs.Delete), if it already exists.
Create the querydef (CurrentDB.CreateQueryDef), using LoginName_Temp as the table name.
Set the RecordSource of your Report to LoginName_Query_Temp.
Open the report.
I don't see what purpose the table myusername_Temp serves here. Is that where the name fields are? If so, avoid the join entirely:
Dim lngEmpNumber As Long
Dim strName As String
Dim strSQL As String
lngEmpNumber = Forms!Reports!txtEmpID
strName = DLookup("[FName] & ' ' & [LName]", "myusername_Temp", "EmpNumber=" & lngEmpNumber
strSQL = "SELECT " & Chr(34) & strName & Chr(34) & " AS [Employee Name], " & _
"CourseName, DateCompleted, tblEmp_SuperAdmin.[Cost Centre] " & _
"FROM tblCourse " & _
"INNER JOIN tblEmpCourses " & _
"ON tblCourse.CourseID = tblEmpCourses.CourseID) " & _
"INNER JOIN tblEmp_SuperAdmin " & _
"ON tblEmp_SuperAdmin.EmpNumber = tblEmpCourses.EmpNo " & _
"WHERE tblEmp_SuperAdmin.EmpNumber = " & lngEmpNumber & _
" ORDER BY CourseName;"
Now, the parentheses may need to be changed in the join (I always do my equi-joins in the Access QBE and let it take care of the getting the order and parens correct!), and my assumptions about the purpose of the temp table may be wrong, but I don't see it being used for anything other than as an intermediate link between tables, so I guessed it must be there to provide the name fields.
If that's wrong, then I'm at a loss as to why the temp table needs to be there.
Also, in your second post you referred to the control on the form as:
Forms!Reports!txtEmpID.Text
...the .Text property of Access controls is accessible only when the control has the focus. You could use the .Value property, but since that's the default property of Access controls, you should just stop after the name of the control:
Forms!Reports!txtEmpID
...you'll see this is how I did it in my suggested code.
I find the idea of your name-based temp table to be highly problematic to begin with. Temp tables don't belong in a front end, and it's not clear to me that it is actually a temp table. If it's temp data, put it in a shared table and key the record(s) to the username. Then you don't have to worry about constructing the table name on the fly.