Filter and Merge Dataset in Vb.Net - vb.net

I am working on VS 2010 - Vb.Net, Having a syntax clarification on Filter & Merge DataSet
My dataset - ds has 23 tables. In which, i need to filter one Table with certain criteria.
tempDs.Merge(ds.Tables("p_tree_categories").Select( "GROUP_CODE <> 'PA.43.948'"))
On writing Merge Syntax,
I am able to see only selected table : p_tree_categories in the tempDs. We need the remaining 22 tables along with the filtered record of p_tree_categories.
How can i achieve this ?

It sounds like you only want the filtered rows of table p_tree_categories. This being the case, I would:
Generate a copy of the p_tree_categories which only contains the rows you are interested in.
Remove the existing p_tree_categories from tempDs.
Merge the copy into tempDs as p_tree_categories.
These steps could be implemented something like this:
Dim originalTable As DataTable = tempDs.Tables("p_tree_categories")
Dim filterView As DataView = New DataView(originalTable)
filterView.RowFilter = "GROUP_CODE <> 'PA.43.948'"
Dim filteredTable As DataTable = filterView.ToTable
filteredTable.TableName = "p_tree_categories"
' Remove old, add the new.
tempDs.Tables.Remove(originalTable)
tempDs.Tables.Add(filteredTable)

Related

update main table from two others with modification of data before updating

I have two tables that I need to update. I have to go through every record on one table then do some modifications to the data then upload the modified
data to another table!
The two tables have 3,000 records and 11,000 records. Plus I also have to
check some info from a third table with about 50 records!
Dim id
Dim fly_SQL
id="user1"
Dim rsc1_conn As ADODB.Connection
Set rsc1_conn = CreateObject("ADODB.Connection")
rsc1_conn.Provider = "SQLOLEDB"
rsc1_conn.ConnectionString = "SERVER=companyserver;UID=" & id &
";Trusted_Connection=Yes;DATABASE=DATAbank" '
rsc1_conn.Open
Set rsc1 = CurrentDb.OpenRecordset("SELECT * FROM main_database",
dbOpenDynaset, dbSeeChanges)
rsc1.movefirst
do until rsc1.EOF
fly_SQL = "Select * from alt_db where alt_db.number = main.net_number"
Set rsc2 = CurrentDb.OpenRecordset(fly_SQL)
do stuff
code = dlookup( "type_def", "third_rec" , alt_db.activity = activity)
The two tables both use net_number as a reference which on the main is primary key unique, but the alt_db has multiple entries.
So basically I have to loop through each net_number on the main, look at the matching net_number on the alt_db then compare an activity field
with a third table to see which field I update on the main! If it's a Project management expense I put it in the main.PM_cost. The net_number in alt_db might repeat for 10 other expenses that need to be funneled into their proper expense categories in the main DB! As an example:
Main table looks like
net_number
first record shows
main.netnumber = 123456
main.cont_cost
main.PM_cost
main.mgmt_cost
alt_db table looks like
alt_db.net_number
alt_db.activity
alt_db.PM_cost
alt_db.const_cost
alt_db.mgmt_cost
third_rec looks like
third_rec.code
third_type
where data can be something like con1 , sabb ,
code type
sauf construction
con1 management
I130 project management
And needed rules:
check alt_db.activity with third_rec.act and return activity type
If activity type is construction then I put the alt_db.cost into main.const_cost
If activity type is project_mgmt then I put the alt_db.cost into main.PM_cost. The alt_db.activity could be con1 or SAF4 and the type is determined by the third_rec table.
Trying to figure out the best (most efficient way) to go about this.
Any suggestions?
The above code will surely be missing proper variable definitions and such but it's just for explaining my dilemma!
I could probably do it with DLookup but I don't think that would be very efficient!
Pete
Best way was to build a query that produces a file filtered data from the Main and alt_db to group the activities by net_number . Then use a case to determine which fields from alt_db to update using the third file and update the result in the proper fields on the main db.

Access SQL Randomizer Not working as intended

I'm using the below mentioned code to select a record ID from an Access Database that wasn't already selected in the last day and add it to an array.
The general goal is that a record that matches the initial "Difficulty" criteria will be retrieved so long as either the record was never selected before OR the record wasn't chosen in the last 2 days. After the loop is done, I should have x amount of unique record ID's and add those onto an array for processing elsewhere.
Private Function RetrieveQuestionID(questionCount As Integer)
' We're using this retrieve the question id's from the database that fit our arrangements.
Dim intQuestArray(0 To questionCount) As Integer
Dim QuestionConnection As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = |DataDirectory|\Database\MillionaireDB.accdb;")
QuestionConnection.Open()
For i As Integer = 1 To intNoOfQuestions
'TODO: If there are no valid questions, pull up any of them that meets the difficulty requirement....
Dim QuestionConnectionQuery As New OleDb.OleDbCommand("SELECT Questions.QuestionID FROM Questions WHERE (((Questions.QuestionDifficulty)=[?])) AND (((Questions.LastDateRevealed) Is Null)) OR (Questions.LastDateRevealed >= DateAdd('d',-2,Date())) ORDER BY Rnd((Questions.QuestionID) * Time());", QuestionConnection)
QuestionConnectionQuery.Parameters.AddWithValue("?", intQuestionDifficulty(i - 1).ToString)
Dim QuestionDataAdapter As New OleDb.OleDbDataAdapter(QuestionConnectionQuery)
Dim QuestionDataSet As New DataSet
QuestionDataAdapter.Fill(QuestionDataSet, "Questions")
intQuestArray(i - 1) = QuestionDataSet.Tables("Questions").Rows(0).Item(0)
Dim QuestionConnectionUpdateQuery As New OleDb.OleDbCommand("UPDATE Questions SET Questions.LastDateRevealed = NOW() WHERE Questions.QuestionID = [?]", QuestionConnection)
QuestionConnectionUpdateQuery.Parameters.AddWithValue("?", intQuestArray(i - 1).ToString)
QuestionConnectionUpdateQuery.ExecuteNonQuery()
Next
QuestionConnection.Close()
Return intQuestArray
End Function
However, looping through the array will show that there are records are somehow being repeated even though the record updates during the loop.
Is there another way to loop through the database and pull up these records? I even attempted to move the .Open() and .Close() statements to within the For...Next loop and I'm given worse results than before.
As Steve wrote, the >= should be a < .
In addition, your WHERE clause is missing parentheses around the OR part.
It should be (without all unnecessary parentheses):
SELECT Questions.QuestionID
FROM Questions
WHERE Questions.QuestionDifficulty=[?]
AND ( Questions.LastDateRevealed Is Null
OR Questions.LastDateRevealed < DateAdd('d',-2,Date()) )
ORDER BY Rnd(Questions.QuestionID * Time());
Also have a look at How to get random record from MS Access database - it is suggested to use a negative value as parameter for Rnd().

Sort a Dataset in visualbasic

I don't know what i doing wrong. I have been on several forums trying to figure out how to sort a table in visual basic.
I have treid with and with out a dataview, but noting seams to work.
I have a logg that the user can do new inserts in. It has 3 columns. "Date", "Tool", "Comment".
When my VB application loads the program reads the table from a Access database and i get my sorting just fine by the sql phrase:
"select * from Logg ORDER BY Logg.Datum DESC"
After a user have uppdated the table i whant to sort it again. I have treid the following, but nothing happens. The order is the same whatever i do.
DS is my Dataset and dw my dataview, and "Datum" the column i whant to sort
DS.Tables("hela").DefaultView.Sort = "Datum DESC"
dw = DS.Tables("hela").DefaultView
For i = 0 To antal_poss - 1
LOGG(i, 0) = dw.Table.Rows(i).Item(3)
LOGG(i, 1) = dw.Table.Rows(i).Item(1)
LOGG(i, 2) = dw.Table.Rows(i).Item(4)
Next i
What am i doing wrong?
In your code you use the DataView to retrieve the Table and then the DataRows, but you extract them following the order on the DataTable.
You need to loop following the order of the DataView.
Something like this
Dim i As Integer = 0
For Each row As DataRowView in dw
LOGG(i, 0) = row.Item(3)
LOGG(i, 1) = row.Item(1)
LOGG(i, 2) = row.Item(4)
i += 1
Next i
Of course this assume that your LOGG array contains enough entries to accomodate every row retrieved. It is the same number of the rows in the DataTable

Unable to read new records from a table

I have a data adapter with 4 tables in a dataset. When I update a new record to the table it appears in the SQL database and the associated datagridivew has been reloaded with the dat in the table, but when I try and read the new record using the following code it can't find the record.
Dim row As DataRow = dsSrvAV.Tables("ServiceAvailability").Select("ID = " & intRecordID).FirstOrDefault()
The same code is used to read other records that were in the database when the application opened, it's just new records that it can't read.
This is the code that writes the new records
Dim newAvailability As DataRow = dsSrvAV.Tables("ServiceAvailability").NewRow()
'Add some data to it
newAvailability("Service_ID") = cboServices.SelectedValue
newAvailability("Date") = Format(dtpDate.Value.ToString, "Short Date")
newAvailability("Downtime") = nudDowntime.Value
newAvailability("Notes") = txtNotes.Text
newAvailability("MajorIncident") = txtMajorIncident.Text
newAvailability("ActionsTaken") = txtActionsTaken.Text
newAvailability("Type") = cboType.SelectedValue
newAvailability("Root_Cause") = txtRootCause.Text
'Add it to the table
dsSrvAV.Tables("ServiceAvailability").Rows.Add(newAvailability)
'Update the adapter
daSrvAv.Update(dsSrvAV, "ServiceAvailability")
dsSrvAV.Tables("ServiceAvailability").AcceptChanges()
Can anyone offer any thoughts as to why this won't allow new records to be read back.
Thanks
Rich
Per comments - this solved the issue.
Close your dsSrvAv dataset, and then re-open it, and then do the select.
Regardng performance: are you adding 1 record per second of 1,000,000. If its 1,000,000 then yes there's an overhead. If its 1 per second there isn't any noticable overhead.

Move a row from one gridview to another

I'm not sure how to go about this. Currently, in the first gridview, is a list of groups a member has access to. The second gridview is bound to a table that contains a list of every type of group and has an Add button which adds it to the first gridview and updates a table adding that group to a member.
This is what I am trying to do:
When the Add button (in the second gridview) for a row is clicked, it will be added to the first one (like it currently does), but I would also like it to disappear from the second gridview. So basically, a group should only be visible in either the first gridview or the second, not both. The problem I have is I don't want to modify the table because obviously the table contains all possible groups. Any suggestions?
I would do all the work on the database side. Data source for first one is:
Select g.*
From membership m
inner join groups g on m.groupid=g.groupid
Where m.userid = #userid
Data source for the second one looks like
Select g.*
From groups g
Where not exists
(Select 1 from membership m
Where m.GroupID=g.GroupID and m.userid = #userid
Then your add button inserts the appropriate row in the table and requeries both grids.
You could simply make changes to the Dataset, then .AcceptChanges and re-bind. This would ensure the data would update on the screen without actually pushing it to the database.
Pseudo example:
Dim dt as Datatable = GetData1(strSQL.toString)
Dim dt2 as Datatable = GetData2(strSQL.toString)
Public Sub MoveRecord(ByVal dt1 as DataTable, ByVal dt2 as Datatable, ByVal index as Integer)
'Record being moved '
Dim dr as Datarow = dt.Rows(index)
dt2.Rows.Add(dr)
dt2.AcceptChanges
dt.Rows.RemoveAt(index)
dt.AcceptChanges
'Bind Gridview
Perhaps store new changes in Viewstate,
Cache, or Session for Paging, Sorting'
End Sub
Of course, this assumes the grids have the same fields. If they don't, you'd have to:
Dim drN as DataRow - dt2.Rows.NewRow
'Assign rows from moving datarow to new datarow'
dt2.Rows.Add(drN)
dt2.AcceptChanges