Hi I am trying to insert data into Navision database from a DataTable. That DataTable contain around 5000 records, if the records count is less then it's working fine but record count is around 5000 I am getting this error.
ERROR - unable to allocate an environment handle.
This is the code I am using
Public Function InsertToHHTTransferLine(ByVal dtTransferLn As DataTable, ByVal hhtNumber As String) As Integer
Dim result As Integer
Dim cn As OdbcConnection
Dim dtTransferLine As DataTable
cn = New OdbcConnection(ConnStr)
Dim SqlStr As String = ""
Try
cn.Open()
dtTransferLine = dtTransferLn
Dim DocType As String
DocType = "Purchase"
Dim cmd As OdbcCommand
Dim hhtNo As String
hhtNo = hhtNumber
If dtTransferLine.Rows.Count > 0 Then
For i As Integer = 0 To dtTransferLine.Rows.Count - 1
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "0" Then
DocType = "Purchase"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "1" Then
DocType = "Transfer Receipt"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "2" Then
DocType = "Transfer Shipment"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "3" Then
DocType = "Stock Count"
End If
Try
SqlStr = "INSERT INTO ""HHT & Navision Line""(""Document Type"",""Document No_"",""HHT No_"",""Line No_"",""Item No_"",""Document Quantity"",""Scan Quantity"",""Unit Price"",""Posted"") VALUES('" & DocType & "','" & dtTransferLine.Rows(i)("DOC_NO").ToString() & "','" & hhtNo & "','" & dtTransferLine.Rows(i)("LINE_NO").ToString() & "','" & dtTransferLine.Rows(i)("ITEM_NO").ToString() & "'," & dtTransferLine.Rows(i)("DOC_QTY").ToString() & "," & dtTransferLine.Rows(i)("SCAN_QTY").ToString() & "," & dtTransferLine.Rows(i)("UNIT_PRICE").ToString() & ",0)"
cmd = New OdbcCommand(SqlStr, cn)
result = cmd.ExecuteNonQuery()
Catch ex As Exception
If (ex.Message.IndexOf("Illegal duplicate key") <> -1) Then
CreateLog(SqlStr, "User1", "Duplicate()", ex.Message)
Else
CreateLog(SqlStr, "User1", "Other()", ex.Message)
End If
'CreateLog(SqlStr, "User1", "Other()", ex.Message)
End Try
Next
End If
Catch ex As Exception
CreateLog(SqlStr, "User1", "InsertToHHTTransferLine()", ex.Message)
result = -1
Finally
cn.Close()
cn.Dispose()
End Try
Return result
End Function
Could be that "cmd" variables need to be disposed before creating new ones?
At least this is the only thing I can see in the code where you are consuming resources in a loop depending on the number of records.
Anyway this should be easy to identify with a debugger, just figure out the line giving you the error, and that will lead you to the answer.
Related
I've got a utility function in a much larger project that updates a backend SQL database. It's currently failing most times I use it, with the error:
There is already an open DataReader associated with this Command which must be closed first.
The code for the function is below:
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Try
Dim cmd As New SqlCommand With {
.Connection = conn
}
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
cmd.Dispose()
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
End Try
End Function
I've gone through the rest of the code to make sure that whenever I have a SQLDataReader declared I later call reader.close(). I added the cmd.Dispose() line to this and all the other ExecuteNonQuery functions I could find - incase that helped?
Are there any other instances/types of reader that might not be being closed?
In the case of an Exception, you aren't disposing your command.
If you don't want to use Using, add a Finally
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Dim cmd As SqlCommand
Try
cmd = New SqlCommand With {.Connection = conn}
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
Finally
cmd.Dispose()
End Try
End Function
but Using might be simpler
Public Function Update_Data(what As String, Optional where As String = "",
Optional table As String = ThisAddIn.defaultTable) As Integer
Using cmd As New SqlCommand With {.Connection = conn}
Try
cmd.CommandText = "UPDATE " & table & " SET " & what
If where <> "" Then
cmd.CommandText &= " WHERE " & where
End If
Update_Data = cmd.ExecuteNonQuery
Catch ex As Exception
Update_Data = 0
Debug.WriteLine("SQL Error updating data:" & vbCrLf & ex.Message)
End Try
End Using
End Function
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.
I have a problem connecting my windows mobile application developed using vb.net in my SQL server 2008 as my back end. Here is my connection string :
Data Source=STEPH-PC\SQL2008;Initial Catalog= MyDB; User ID = myusername; Password = mypassword;
It always give me an error that SQL server does not exist or access denied. Any help on how to solve this issue?
1- Testing connection Server versus Pocket PC:
First at all test if your SQL Server CE mobile agent connects to SQL Server CE Server agent. To do this you have to install SQL Server CE 3.5 in the server and in your Pocket PC. Search in google How to install SQL Server CE 3.5. In the process you create a Virtual Directory in Server and in that directory you got a file sqlcesa35.dll, so to test the connection in your Pocket PC browser write: http://ipserver/virtual_directory/sqlcesa35.dll (of course ipserver must be your server IP and virtual_directory must be your virtual directory name). Doing this you have to get in your Pocket PC the message:
Microsoft SQL Server Compact
Server Agent
At this point I have to mention that always you must have internet connection.
2- Retrieving files from the server (this is a sample code, not debugged, I only have taken some parts from other project and put them here).
Function get_companies(ByVal sSucursal As String, ByVal cn_Interface As System.Data.SqlServerCe.SqlCeConnection, _
ByVal cmd_Interface As System.Data.SqlServerCe.SqlCeCommand, ByVal dr_Interface As System.Data.SqlServerCe.SqlCeDataReader) As Boolean
get_companies = False
Dim _strRemoteConnect As String
Dim _strLocalConnect As String
Dim _strInternetURL As String = sInternetURL
'The last variable sInternetURL is something like: http://ip_server/virtual_directory/sqlcesa35.dll
_strRemoteConnect = "Provider=SQLOLEDB;Data Source=" & sIPSQLServer & ";Initial Catalog=" & sBDSQLServer & ";User Id=" & sUserSQLServer & ";Password=" & sClaveSQLServer
'sIPSQLServer is the server ip where is running SQL Server
'sBDSQLServer is your DataBase server.
_strLocalConnect = "Data Source=" & sPath & "\" & sDataBase_Interface & "; Password=" & sPassword
'sPath is your directory in your Pocket PC, begings with \
'sDataBase_Interface is the database in my Pocket PC, an .sdf file
Dim rda As System.Data.SqlServerCe.SqlCeRemoteDataAccess = New System.Data.SqlServerCe.SqlCeRemoteDataAccess
rda.InternetLogin = sUserInternet 'a valid user in your domain
rda.InternetPassword = sClaveInternet
rda.InternetUrl = _strInternetURL
rda.LocalConnectionString = _strLocalConnect
Do While True
Try
'In server database there is a table: Monedas
rda.Pull("_Monedas", "Select Moneda, Descripcion, Abreviada From Monedas Where Sucursal = '" & sSucursal & "'", _
_strRemoteConnect, System.Data.SqlServerCe.RdaTrackOption.TrackingOff)
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Loop
'read the data received, just testing, may be this code not to be here because you process the data outside the function.
Try
cmd_Interface.CommandText = "Select Moneda, Descripcion, Abreviada From _Monedas"
dr_Interface = cmd_Interface.ExecuteReader()
Do While dr_Interface.Read()
messagebox.show("Moneda = " & dr_interface("Moneda") & " - " & dr_interface("Descripcion") & " - " & dr_interface("Abreviada"), _
"Currencies Received", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
Loop
get_companies = true
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
Finally
'If cn_Interface.State <> ConnectionState.Closed Then
' cmd_Interface.Dispose()
' cn_Interface.Close()
' cn_Interface.Dispose()
'End If
End Try
End Function
3- Excecuting a sentence in Database Server from your Pocket PC and Transferring data from Pocket to Server:
Function EnviarClientesNuevos(ByVal sSucursal As String, ByVal sZona As String, ByVal sRuta As String) As Boolean
Dim sLineas As String
Dim nRegs As Integer
Dim cn_Interface As System.Data.SqlServerCe.SqlCeConnection
Dim cmd_Interface As System.Data.SqlServerCe.SqlCeCommand
EnviarClientesNuevos = False
Dim _strRemoteConnect As String
Dim _strLocalConnect As String
Dim _strInternetURL As String = sInternetURL
_strRemoteConnect = "Provider=SQLOLEDB;Data Source=" & sIPSQLServer & ";Initial Catalog=" & sBDSQLServer & ";User Id=" & sUserSQLServer & ";Password=" & sClaveSQLServer
_strLocalConnect = "Data Source=" & sPath & "\" & sDataBase_Interface & "; Password=" & sPassword
Dim rda As System.Data.SqlServerCe.SqlCeRemoteDataAccess = New System.Data.SqlServerCe.SqlCeRemoteDataAccess
rda.InternetLogin = sUserInternet
rda.InternetPassword = sClaveInternet
rda.InternetUrl = _strInternetURL
rda.LocalConnectionString = _strLocalConnect
Do While True
If DropTableE("_NEW_CLIENTES_XX") Then
Try
'_NEW_CLIENTES_XX is a table in your SQL Server (The server, not the Pocket)
rda.Pull("_NEW_CLIENTES_XX", "Select Id, Sucursal, Zona, CodCli, Nombre, Direccion, Ruc, Clase, Ruta " & _
"FROM _NEW_CLIENTES_XX WHERE Sucursal = ''", _strRemoteConnect, SqlServerCe.RdaTrackOption.TrackingOn)
'In where clause I compare to '' because I only need the structure
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Function
End Try
End If
Loop
Try
'--
cn_Interface = New System.Data.SqlServerCe.SqlCeConnection
cn_Interface.ConnectionString = "Data Source=" & sPath & "\" & sDataBase_Interface & ";Password=" & sPassword
cn_Interface.Open()
cmd_Interface = cn_Interface.CreateCommand()
cmd_Interface.CommandType = CommandType.Text
'--
'here I have an open connection to another database in my Mobile Device. Here I have to mention that I work with 2 databases in my mobile device:
'One database for getting the data from server, I only use it when I get data from server and when I send data to server
'and other database which is my main database, the database that is used all the day storing customers transactions.
'here I already have open (outside this function) the connection to this second database, but the sentence are the same above,
'something like this:
'Try
' cn = New System.Data.SqlServerCe.SqlCeConnection
' cn.ConnectionString = "Data Source=" & sPath & "\" & sDataBase_Ppal & ";Password=" & sPassword
' cn.Open()
' cmd = cn.CreateCommand()
' cmd.CommandType = CommandType.Text
'Read the data from my main Pocket PC database
cmd.CommandText = "SELECT CodCli, Nombre, Direccion, Ruc, Clase From CLIENTES WHERE CLASE IN ('N', 'M')"
dr = cmd.ExecuteReader()
Do While dr.Read()
'Insert the data in the table structure that I get above.
'remember that this table is in the database that only is used when transferring data, its a temporal database.
cmd_Interface.CommandText = "INSERT INTO _NEW_CLIENTES_XX (Sucursal, Zona, CodCli, Nombre, Direccion, Ruc, Clase, Ruta) " & _
"VALUES('" & sSucursal & "', '" & sZona & "', " & dr("CodCli") & ", '" & _
dr("Nombre") & "', '" & dr("Direccion") & "', '" & dr("Ruc") & "', '" & _
dr("Clase") & "', '" & sRuta & "')"
nRegs = cmd_Interface.ExecuteNonQuery()
Loop
dr.Close() : dr.Dispose()
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)
Exit Function
Finally
Try
dr.Close()
dr.Dispose()
Catch ex As Exception
End Try
'If cn.State <> ConnectionState.Closed Then
' cmd.Dispose()
' cn.Close()
' cn.Dispose()
'End If
If cn_Interface.State <> ConnectionState.Closed Then
cmd_Interface.Dispose()
cn_Interface.Close()
cn_Interface.Dispose()
End If
End Try
Do While True
Try
'I excecute a sentence in the Server. I delete the data in _NEW_CLIENTES_XX which is a work table in SQL server.
rda.SubmitSql("Delete From _NEW_CLIENTES_XX Where Sucursal = '" & sSucursal & "' AND Zona = '" & sZona & "' And Ruta = '" & sRuta & "'", _strRemoteConnect)
'I send the data to server
rda.Push("_NEW_CLIENTES_XX", _strRemoteConnect, System.Data.SqlServerCe.RdaBatchOption.BatchingOn)
EnviarClientesNuevos = True
Exit Do
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Exit Function
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Function
End Try
Loop
End Function
Generalities:
Function DropTableP(ByVal sTabla As String) As Boolean
'Dim cn_Interface As System.Data.SqlServerCe.SqlCeConnection
'Dim cmd_Interface As System.Data.SqlServerCe.SqlCeCommand
'Dim dr_Interface As System.Data.SqlServerCe.SqlCeDataReader
Dim nRegs As Integer
Try
'cn_Interface = New System.Data.SqlServerCe.SqlCeConnection("Data Source=" & sPath & "\" & sDataBase_Ppal & "; Password=" & sPassword)
'cn_Interface.Open()
'cmd_Interface = cn_Interface.CreateCommand()
'cmd_Interface.CommandType = CommandType.Text
cmd.CommandText = "Select TABLE_NAME From INFORMATION_SCHEMA.TABLES Where TABLE_NAME = '" & sTabla & "'"
dr = cmd.ExecuteReader()
If dr.Read() Then
dr.Close()
dr.Dispose()
cmd.CommandText = "DROP TABLE " & sTabla
nRegs = cmd.ExecuteNonQuery()
DropTableP = True
Else
dr.Close()
dr.Dispose()
DropTableP = True
End If
Catch exc As System.Data.SqlServerCe.SqlCeException
ShowErrorSqlServerCE(exc)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'If cn_Interface.State <> ConnectionState.Closed Then
' cn_Interface.Close()
' cn_Interface.Dispose()
'End If
End Try
End Function
Sub ShowErrorSqlServerCE(ByVal exc As System.Data.SqlServerCe.SqlCeException)
Dim bld As New System.Text.StringBuilder
Dim err As System.Data.SqlServerCe.SqlCeError
Dim errorCollection As System.Data.SqlServerCe.SqlCeErrorCollection = exc.Errors
Dim errPar As String
Dim numPar As Integer
' Loop through all of the errors.
For Each err In errorCollection
bld.Append(ControlChars.Cr & " Error Code: " & err.HResult.ToString("X"))
bld.Append(ControlChars.Cr & " Message : " & err.Message)
bld.Append(ControlChars.Cr & " Minor Err.: " & err.NativeError)
bld.Append(ControlChars.Cr & " Source : " & err.Source)
' Loop through all of the numeric parameters for this specific error.
For Each numPar In err.NumericErrorParameters
If numPar <> 0 Then
bld.Append(ControlChars.Cr & " Num. Par. : " & numPar.ToString())
End If
Next numPar
' Loop through all of the error parameters for this specific error.
For Each errPar In err.ErrorParameters
If errPar <> [String].Empty Then
bld.Append(ControlChars.Cr & " Err. Par. : " & errPar)
End If
Next errPar
' Finally, display this error.
MessageBox.Show(bld.ToString(), "SQL Server CE")
' Empty the string so that it can be used again.
bld.Remove(0, bld.Length)
Next err
End Sub
As I said above: the code that I put here needs to be debugged...I have only extracted some parts from my project and put here. Hope this will help you!
I have the following problem, I am developing a Clinic application using vb.net, the doctor has the ability to add medical information using checkboxes checkbox2.text = "Allergy" textbox15.text is the notes for Allergy, I want to insert the record if the patient's FileNo(Textbox2.text) doesn't exist, if it does then update the notes only, so far I was able to update it after 3 button clicks I don't know why????
any help is appreciated :)
thanks in advance
Dim connection3 As New SqlClient.SqlConnection
Dim command3 As New SqlClient.SqlCommand
Dim adaptor3 As New SqlClient.SqlDataAdapter
Dim dataset3 As New DataSet
connection3.ConnectionString = ("Data Source=(LocalDB)\v11.0;AttachDbFilename=" + My.Settings.strTextbox + ";Integrated Security=True;Connect Timeout=30")
command3.CommandText = "SELECT ID,Type FROM Medical WHERE FileNo='" & TextBox2.Text & "';"
connection3.Open()
command3.Connection = connection3
adaptor3.SelectCommand = command3
adaptor3.Fill(dataset3, "0")
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
For countz = 0 To count9
Dim A2 As String = dataset3.Tables("0").Rows(countz).Item("Type").ToString
Dim B2 As Integer = dataset3.Tables("0").Rows(countz).Item("ID")
TextBox3.Text = A2
If A2 = CheckBox1.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox22.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox1.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
ElseIf A2 = CheckBox2.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox15.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox2.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Next
Else
If CheckBox1.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox1.Text & "',N'" & TextBox22.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
If CheckBox2.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox2.Text & "',N'" & TextBox15.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
I think one of your problems may be related to your reducing the count of your table rows by 1 and then testing it above 0:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
Try changing to:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count
If count9 > 0 Then
Also, make sure one of the check-boxes (CheckBox1 or CheckBox2) mentioned later in your code is ticked.
-- EDIT --
Sorry - didn't explain why! The reason is that the majority of array/list like structures in .NET are zero based (i.e. start counting from 0 instead of 1).
The best course of action for you is to maximize your productivity by allowing SQL to do what it does best. Assuming you are using SQL Server 2008, the MERGE function is an excellent use case for the conditions that you have supplied.
Here is a very basic example that is contrived based upon some of your code:
CREATE PROCEDURE [dbo].[csp_Medical_Merge]
#MType int, #FileNo varchar(20), #MNotes varchar(max), #ID int, #OtherParams
AS
BEGIN
MERGE INTO [DatabaseName].dbo.Medical AS DEST
USING
(
/*
Only deal with data that has changed. If nothing has changed,
then move on.
*/
SELECt #MType, #MNotes, #FileNo, #ID, #OtherParams
EXCEPT
Select [Type], MNotes, FileNo, ID, OtherFields from [DatabaseName].dbo.Medical
) As SRC ON SRC.ID = DEST.ID
WHEN MATCHED THEN
UPDATE SET
DEST.MNOTES = SRC.MNOTES,
DEST.FileNo = SRC.FileNo,
DEST.Type = SRC.Type
WHEN NOT MATCHED BY TARGET THEN
INSERT (FieldsList)
VALUEs (FileNo, MNotes, etc, etc);
END
GO
I have to display data from VB.NET code to crystal report...and I'm doing everything from the code, so the problem is that I have to display multiple data from for-each loop, this is the code:
Private Sub Print_Row(ByVal pp As Boolean)
Dim rptDokument As New ReportDocument, brkop As Integer
Dim rw_mat As DataRow
Dim cn As OracleClient.OracleConnection = New OracleClient.OracleConnection(Gdb_conn)
' Objects used to set the parameters in the report
Dim pCollection As New CrystalDecisions.Shared.ParameterValues
Dim pTSJ As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pNaziv As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pKolicina As New CrystalDecisions.Shared.ParameterDiscreteValue
Dim pTezina As New CrystalDecisions.Shared.ParameterDiscreteValue
Try
rptDokument.Load(Gpath & "PakLista.rpt")
pTSJ.Value = barcode.Text
pCollection.Add(pTSJ)
rptDokument.DataDefinition.ParameterFields("pTSJ").ApplyCurrentValues(pCollection)
cn.Open()
Dim myQuery As String = "SELECT S.TSJ,M.NAZ_MAT, S.IBRMAT, S.KOLICINA, S.TEZINA " & _
"FROM TWM_SADRZAJ S, TWM_MATER M, TWM_ATRIBUT A, TWM_PAKIR PAK " & _
"WHERE(S.VLASNIK_MP = M.VLASNIK_MP) " & _
"AND S.IBRMAT = M.IBRMAT " & _
"AND S.ATR_ID = A.ATR_ID (+) " & _
"AND PAK.VLASNIK_MP (+) = S.VLASNIK_MP " & _
"AND PAK.IBRMAT (+) = S.IBRMAT " & _
"AND PAK.PAK (+) = S.PAK " & _
"AND (S.TSJ = '" & barcode.Text & "') " & _
"ORDER BY S.IBRMAT"
Dim da As OracleClient.OracleDataAdapter = New OracleClient.OracleDataAdapter(myQuery, cn)
Dim ds As New DataSet
da.Fill(ds, "TWM_SADRZAJ")
For Each rw_mat In ds.Tables("TWM_SADRZAJ").Rows
If (rw_mat.Item("NAZ_MAT") Is DBNull.Value) Then
pNaziv.Value = ""
Else
pNaziv.Value = CStr(rw_mat.Item("NAZ_MAT"))
End If
If (rw_mat.Item("KOLICINA") Is DBNull.Value) Then
pKolicina.Value = ""
Else
pKolicina.Value = CStr(rw_mat.Item("KOLICINA"))
End If
If (rw_mat.Item("TEZINA") Is DBNull.Value) Then
pTezina.Value = ""
Else
pTezina.Value = CStr(rw_mat.Item("TEZINA"))
End If
pCollection.Add(pNaziv)
rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina)
rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina)
rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
Next rw_mat
If pp Then
Dim frm As New frmPrint_preview
frm.crvDocument.ReportSource = rptDokument
frm.ShowDialog()
Else
Dim pd As New PrintDialog
pd.PrinterSettings = New PrinterSettings
If pd.ShowDialog(Me) Then
For brkop = 1 To pd.PrinterSettings.Copies
rptDokument.PrintOptions.PrinterName = pd.PrinterSettings.PrinterName
rptDokument.PrintToPrinter(1, False, 1, 99999)
Next brkop
End If
End If
Catch Exp As LoadSaveReportException
MsgBox("Incorrect path for loading report.", MsgBoxStyle.Critical, "Load Report Error")
Catch Exp As System.Exception
MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
The problem is in this section:
pCollection.Add(pNaziv) rptDokument.DataDefinition.ParameterFields("pNaziv").ApplyCurrentValues(pCollection)
pCollection.Add(pKolicina) rptDokument.DataDefinition.ParameterFields("pKolicina").ApplyCurrentValues(pCollection)
pCollection.Add(pTezina) rptDokument.DataDefinition.ParameterFields("pTezina").ApplyCurrentValues(pCollection)
It has to be out side for each loop to gather all the data, but the problem is no mater where i put this code it only displays the last record from data row for let's say 5 records in crystal report...I know it's peace of cake but I'm relay stuck here so I would appreciate a little help.
It is normal that the report only shows the last record, because you try to pass the data as parameters. Instead you should set the datasource programmatically, you can see how to do it here ^
ReportDocument.SetDataSource Method
and here you can find a complete example of how to create a typed dataset to use on your report
Create report by vb.net and crystal report