This question already has an answer here:
DataTable.Load() Throws Error: Undefined function 'CountWeekDays' in expression
(1 answer)
Closed 6 years ago.
i used this funtion to concatenate datarows..
Public Function GetList(SQL As String _
, Optional ColumnDelimeter As String = ", " _
, Optional RowDelimeter As String = vbCrLf) As String
'PURPOSE: to return a combined string from the passed query
'ARGS:
' 1. SQL is a valid Select statement
' 2. ColumnDelimiter is the character(s) that separate each column
' 3. RowDelimiter is the character(s) that separate each row
'RETURN VAL: Concatenated list
'DESIGN NOTES:
'EXAMPLE CALL: =GetList("Select Col1,Col2 From Table1 Where Table1.Key = " & OuterTable.Key)
Const PROCNAME = "GetList"
Const adClipString = 2
Dim oConn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim sResult As String
On Error GoTo ProcErr
Set oConn = CurrentProject.Connection
Set oRS = oConn.Execute(SQL)
sResult = oRS.GetString(adClipString, -1, ColumnDelimeter, RowDelimeter)
If Right(sResult, Len(RowDelimeter)) = RowDelimeter Then
sResult = Mid$(sResult, 1, Len(sResult) - Len(RowDelimeter))
End If
GetList = sResult
oRS.Close
oConn.Close
CleanUp:
Set oRS = Nothing
Set oConn = Nothing
Exit Function
ProcErr:
' insert error handler
Resume CleanUp
End Function
the query i used is
SELECT OB.Operation_Type, OB.Machine_Type, OB.Attatchment, GetList("Select Operation_Name From OB As T1 Where T1.Operation_Type = """ & [ob].[Operation_Type] & """ and T1.Machine_Type = """ & [ob].[Machine_Type] & """ and T1.Attatchment = """ & [ob].[Attatchment] & """ ",""," + ") AS Expr1
FROM ob
GROUP BY ob.Operation_Type, Machine_Type, Attatchment;
Now i need to call this query from vb.net
i tried as follows::
myConnection.Open()
Dim db As New OleDb.OleDbDataAdapter
Dim cn As New OleDb.OleDbConnection
Dim dt As New DataTable
Dim ds As New DataSet
Dim cmd As New OleDbCommand("Query", myConnection)
Try
cmd.Connection = myConnection
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Query"
db.SelectCommand = cmd
db.Fill(dt)
Me.DataGridView1.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
myConnection.Close()
this is giving error as follows
"Undefined function 'GetList' in expression."
Please Help
Thank You!
The error message is clear. You send the SQL string to Access which then looks for the function GetList which it, of course, cannot find.
You will have to rethink your concept.
Related
i confused why mySqlDataReader.Read stuck on the last record and doesnt EOF ..
Here's my private function for executeSql :
Private Function executeSQL(ByVal str As String, ByVal connString As String, ByVal returnRecordSet As Boolean) As Object
Dim cmd As Object
Dim objConn As Object
Try
If dbType = 2 Then
cmd = New MySqlCommand
objConn = New MySqlConnection(connString)
Else
cmd = New OleDbCommand
objConn = New OleDbConnection(connString)
End If
'If objConn.State = ConnectionState.Open Then objConn.Close()
objConn.Open()
cmd.Connection = objConn
cmd.CommandType = CommandType.Text
cmd.CommandText = str
If returnRecordSet Then
executeSQL = cmd.ExecuteReader()
executeSQL.Read()
Else
cmd.ExecuteNonQuery()
executeSQL = Nothing
End If
Catch ex As Exception
MsgBox(Err.Description & " #ExecuteSQL", MsgBoxStyle.Critical, "ExecuteSQL")
End Try
End Function
And this is my sub to call it where the error occurs :
Using admsDB As MySqlConnection = New MySqlConnection("server=" & rs("server") & ";uid=" & rs("user") & ";password=" & rs("pwd") & ";port=" & rs("port") & ";database=adms_db;")
admsDB.Open()
connDef.Close()
rs.Close()
'get record on admsdb
Dim logDate As DateTime
Dim str As String
str = "select userid, checktime from adms_db.checkinout in_out where userid not in (select userid " &
"from adms_db.checkinout in_out join (select str_to_date(datetime,'%d/%m/%Y %H:%i:%s') tgl, fid from zsoft_bkd_padang.ta_log) ta " &
"on ta.fid=userid and tgl=checktime)"
Dim rsAdms As MySqlDataReader = executeSQL(str, admsDB.ConnectionString, True)
Dim i As Integer
'This is where the error is, datareader stuck on the last record and doesnt EOF
While rsAdms.HasRows
'i = i + 1
logDate = rsAdms(1)
'save to ta_log
str = "insert into ta_log (fid, Tanggal_Log, jam_Log, Datetime) values ('" & rsAdms(0) & "','" & Format(logDate.Date, "dd/MM/yyyy") & "', '" & logDate.ToString("hh:mm:ss") & "', '" & logDate & "')"
executeSQL(str, oConn.ConnectionString, False)
rsAdms.Read()
End While
'del record on admsdb
str = "truncate table checkinout"
executeSQL(str, admsDB.ConnectionString, False)
End Using
i'm new to vbnet and really have a little knowledge about it,, please help me,, and thank you in advance..
The issue is that you're using the HasRows property as your loop termination expression. The value of that property never changes. Either the reader has rows or it doesn't. It's not a check of whether it has rows left to read, so reading has no effect.
You are supposed to use the Read method as your flag. The data reader begins without a row loaded. Each time you call Read, it will load the next row and return True or, if there are no more rows to read, it returns False.
You normally only use HasRows if you want to do something special when the result set is empty, e.g.
If myDataReader.HasRows Then
'...
Else
MessageBox.Show("No matches found")
End If
If you don't want to treat an empty result set as a special case then simply call Read:
While myDataReader.Read()
Dim firstFieldValue = myDataReader(0)
'...
End While
Note that trying to access any data before calling Read will throw an exception.
When running the expression below I get an error saying:
Data type mismatch in criteria expression
The message boxes are used to identify where error happened, it gets to checkpoint 1 then it stops!
Dim table2 As New DataTable
Dim recordcount2 As Integer
Dim command2 As String = "SELECT * FROM [Results] where " & "[TestID] = " & " '" & CInt(LocationID) & "'"
Dim adapter2 As New OleDb.OleDbDataAdapter(command2, conn)
table2.Clear()
MsgBox("Checkpoint 1")
recordcount2 = adapter2.Fill(table2)
MsgBox("Checkpoint 2")
The code is in this section of my program:
Try
'Defining variables
Dim table As New DataTable
Dim command As String
Dim recordCount As Integer
Dim LocationID As Integer
command = "SELECT * FROM [Test] where " & "[MachineID] = " & " '" & machineID & "'" 'SQL command to find if there is a usename stored with that is in username text box
Dim adapter As New OleDb.OleDbDataAdapter(command, conn) 'adapter
table.Clear() 'adding data to a table.
recordCount = adapter.Fill(table)
If recordCount <> 0 Then
For i = 0 To recordCount
Try
LocationID = CInt(table.Rows(i)(0))
Dim table2 As New DataTable
Dim recordcount2 As Integer
Dim command2 As String = "SELECT * FROM [Results] where " & "[TestID] = " & " '" & CInt(LocationID) & "'"
Dim adapter2 As New OleDb.OleDbDataAdapter(command2, conn)
table2.Clear()
MsgBox("Checkpoint 1")
recordcount2 = adapter2.Fill(table2)
MsgBox("Checkpoint 2")
If recordcount2 <> 0 Then
For x = 0 To recordcount2
MsgBox("yay1")
Dim TestID As String = table2.Rows(x)(1)
Dim Thickness As String = table2.Rows(x)(2)
Dim TargetFilter As String = table2.Rows(x)(9)
Dim SNR As String = table2.Rows(x)(3)
Dim STD As String = table2.Rows(x)(4)
MsgBox("yay2")
Dim M1 As String = table2.Rows(x)(5)
Dim M2 As String = table2.Rows(x)(6)
Dim kVp As String = table2.Rows(x)(7)
Dim mAs As String = table2.Rows(x)(8)
MsgBox("yay3")
Dim CNR As Short = (CLng(M1) - CLng(M2)) / 2
MsgBox("Further")
dgvViewData.Rows.Add(TestID, Thickness, CStr(SNR), CStr(STD), CStr(M1), CStr(M2), kVp, mAs, CStr(CNR))
Next
Else
MsgBox("RIP")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Next
Else
MsgBox("There data for this machine.")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Code on button
Try
Dim table As New DataTable
Dim command As String
Dim recordCount As Integer
Dim TestNum As String = "1"
command = "SELECT * FROM [Results] where " & "[TestID] = " & " '" & CStr(TestNum) & "'"
Dim adapter As New OleDb.OleDbDataAdapter(command, conn)
table.Clear()
recordCount = adapter.Fill(table)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Your locationID parameter has to be a string to be concatenated into your select statement. I'm assuming its an integer which is causing your datatype mismatch.
I'm quite sure that your LocationID is an integer, thus should be concatenated as is, so the SQL should read:
Dim command2 As String = "SELECT * FROM [Results] where [TestID] = " & CStr(LocationID) & ""
I am trying to check if value from label1 exist in dbf file column named : "NALOG,C,8". Header in DBF file I can not change, 'cause it represents column's format and field size. But with that I get this error : "Syntax error (comma) in query expression "NALOG,C,8 = #NAL"
Here is complete code :
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "NALOG,C,8"
'Dim SQLstr As String = "SELECT * FROM " & DBF_File
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV;User ID=Admin;Password="
'cmd = New OleDbCommand("SELECT * FROM " & DBF_File)
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE " & ColName & " = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", Label1.Text)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST" & TextBox1.Text
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
end using
Thanks.
If you have a column that is named this:
Dim ColName As String = "NALOG,C,8"
Then I would change it too this:
Dim ColName As String = "[NALOG,C,8]"
Use this instead:
Dim ColName As String = "NALOG"
Guy's Cant seem to find my error in VB.Net ! my codes are all right ! but the function still won't save on the database cause of Syntax error in my Insert into statement ! Please help me ! :D!
This is my Code!:D!
Dim Transaction As OleDb.OleDbTransaction = Nothing
Dim Connection As OleDb.OleDbConnection = Nothing
Try
Connection = New OleDb.OleDbConnection(My.Settings.POS_CanteenConnectionString)
Connection.Open()
Transaction = Connection.BeginTransaction
Dim SQL As String = "Insert into Recipt (ReciptDate,ReciptTotal)Values(:0,:1)"
Dim CMD1 As New OleDb.OleDbCommand
CMD1.Connection = Connection
CMD1.Transaction = Transaction
CMD1.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", Now.Date)
CMD1.Parameters.AddWithValue(":1", TextBox4.Text)
CMD1.ExecuteNonQuery()
CMD1.Dispose()
SQL = "Select Max(ReciptID) As MAXID from Recipt"
Dim CMD2 As New OleDb.OleDbCommand
CMD2.Connection = Connection
CMD2.Transaction = Transaction
CMD2.CommandText = SQL
Dim ReciptID As Long = CMD2.ExecuteScalar()
CMD2.Dispose()
Dim I As Integer
For I = 0 To DGV3.Rows.Count - 1
Dim BarCode As String = DGV3.Rows(I).Cells(0).Value
Dim BuyPrice As Decimal = DGV3.Rows(I).Cells(2).Value
Dim SellPrice As Decimal = DGV3.Rows(I).Cells(3).Value
Dim ItemCount As Integer = DGV3.Rows(I).Cells(4).Value
Dim CMD3 As New OleDb.OleDbCommand
SQL = "Insert to ReciptDetails" & _
"(ReciptID,BarCode,ItemCount,ItemBuyPrice,ItemSellPrice)" & _
"Values" & _
"(:0 ,:1 ,:2 ,:3 ,:4 )"
CMD3.Connection = Connection
CMD3.Transaction = Transaction
CMD3.CommandText = SQL
CMD3.Parameters.AddWithValue(":0", ReciptID)
CMD3.Parameters.AddWithValue(":1", BarCode)
CMD3.Parameters.AddWithValue(":2", BuyPrice)
CMD3.Parameters.AddWithValue(":3", ItemCount)
CMD3.Parameters.AddWithValue(":4", SellPrice)
CMD3.ExecuteNonQuery()
CMD3.Dispose()
Next
Transaction.Commit()
Transaction.Dispose()
Connection.Close()
Connection.Dispose()
DGV3.Rows.Clear()
TextBox4.Text = ""
Catch ex As Exception
If Transaction IsNot Nothing Then
Transaction.Rollback()
End If
If Connection IsNot Nothing Then
If Connection.State = ConnectionState.Open Then
Connection.Close()
End If
End If
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "ERROR")
End Try
Firstly, I don't think sp parameters are called by : prefix, you should use # instead. you'll therefore need to replace the .AddWithValue (everywhere) by;
CMD1.Parameters.AddWithValue("#0", Now.Date)
CMD1.Parameters.AddWithValue("#1", TextBox4.Text)
Secondly, I think the Insert syntax isn't right, you've place TO instead of INTO and space missing. Try this;
SQL = "Insert into ReciptDetails " & _
"(ReciptID, BarCode, ItemCount, ItemBuyPrice, ItemSellPrice)" & _
" Values (#0, #1, #2, #3, #4)"
I am working on a report in SSRS2005 where I need to use some VB.NET code to go out to a different database than the one in the report and return a list of integers (user IDs). I need to use some VB.NET code to do this. I have some code that 'works' in the sense that it does not throw any errors and I get values returned. However, I only get the first value and not the entire list. Here is what I have so far:
Public Function GetUsers(ByVal param As Integer) As String
Dim sqlCon As New System.Data.SqlClient.SqlConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim dRet As String
Dim sCmdText As String
sqlCon.ConnectionString = "data source=myServer;initial catalog=myDatabase;Integrated Security=true"
cmd = New System.Data.SqlClient.SqlCommand
sCmdText = "SELECT UsersRowID FROM dbo.tvf_Get_Users("
'cmd.CommandType = CommandType.Text
cmd.Connection = sqlCon
cmd.CommandTimeout = 0
sCmdText = sCmdText & param
sCmdText = sCmdText & ")"
cmd.CommandText = sCmdText
If sqlCon.State <> System.Data.ConnectionState.Open Then
sqlCon.Open()
End If
dRet = cmd.ExecuteScalar() & ""
sqlCon.Close()
Return dRet
End Function
I have tried experimenting with using the DataSet data type but I get error messages that I cannot cast DataSet as a String.
Any ideas what I need to do to get this to work?
modify your code to the following
Public Function GetUsers(ByVal param As Integer) As String
'
Dim sqlCon As New System.Data.SqlClient.SqlConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim dtAdapter As Data.SqlClient.SqlDataReader
Dim dRet As String
Dim sCmdText As String
'
'connection
sqlCon.ConnectionString = "data source=myServer;initial catalog=myDatabase;Integrated Security=true"
sqlCon.Open()
'
'query
sCmdText = "SELECT UsersRowID FROM dbo.tvf_Get_Users(" & param & ")"
'
'command
cmd = New System.Data.SqlClient.SqlCommand(sCmdText, sqlCon)
cmd.CommandTimeout = 0
'
'main course
If cmd.Connection.State = Data.ConnectionState.Closed Then cmd.Connection.Open()
dtAdapter = cmd.ExecuteReader(Data.CommandBehavior.CloseConnection)
If dtAdapter.HasRows Then
While dtAdapter.Read()
' following assumes "dbUserId" is the userid field in the database
' also use pipe "|" to split the userid's whens theres more than one
' this is so you can still use STRING as the function return and not an ARRAY
dRet = dRet & dtAdapter.GetValue(dtAdapter.GetOrdinal("dbUserId")) & "|"
End While
End If
If cmd.Connection.State <> Data.ConnectionState.Closed Then cmd.Connection.Close()
Return dRet
'
End Function