SCOPE_IDENTITY() after TableAdapter Update - vb.net

I've updated my TableAdapter's advanced options, so it would Refresh the data table.
I'm looking to retrieve the SCOPE_IDENTITY of the new added row, right after I use TableAdapter.Update.
How can this be achieved?
Thanks!

The TableAdapter will insert the SCOPE_IDENTITY automatically at the end of the insert statement. The DataRow contains the newly created identity value after the insert. Just don't set the PK column before you add the row to the table and update it via the TableAdapter.
Dim daLocation As New LocationTableAdapter() ' the TableAdapter
Dim newLocation = Location.NewLocationRow() ' the new DataRow
newLocation.Name = "Berlin"
Location.AddLocationRow(newLocation)
' now update the DataTable or the DataRow with the TableAdapter
Dim numRowsUpdated As Int32 = daLocation.Update(newLocation)
Dim id As Int32 = newLocation.idLocation ' now the new ID is available

Related

MS Access Database insert values on a column using vba and sql query

Is there any way to add a column into an MS Access database using VBA and SQL query and then insert values using formulas from other column.
As an example, I want to create a column employee and it should have calculated values on all the records. I want to use LEFT(col2, 3) in the employee field.
This is my code:
Sub createcolumn()
Dim objAccess As Object
Set objAccess = CreateObject("Access.Application")
Call objAccess.OpenCurrentDatabase("H:\VBA\Array Practice\Database1array.accdb")
objAccess.CurrentProject.Connection.Execute ("ALTER TABLE Company ADD COLUMN employee CHAR ")
End Sub
Sub insertvalues()
Dim objAccess As Object
Set objAccess = CreateObject("Access.Application")
Call objAccess.OpenCurrentDatabase("H:\VBA\Array Practice\Database1array.accdb")
objAccess.CurrentProject.Connection.Execute "INSERT INTO Employee (Gross) VALUES LEFT([full_name], 3)"
End Sub
I am able to create a new column but could't insert the value.
You can directly update the table using column FULL_NAME instead of inserting. I have tested the following code and it is working.
Sub test()
Dim dbs As Database
Set dbs = OpenDatabase("Database1.accdb")
dbs.Execute "UPDATE EMPLOYEE SET GROSS=LEFT(FULL_NAME, 3)"
dbs.Close
End Sub
You added a column to a table named Company, but you are attempting to insert values to a table named employee.
If the table named company as records then an update statement is what you need to add values into the new column employee, but if the table does not have any record, then an insert statement can be used to add values into the employee field.

How to store server auto generated value to Primary key column

I was working on an application that uses sql server database. I the auto generated value for the primary key to be stored into dataset. I was using the below code. But the problem is my primary key column ie, ProdNum is readonly. For that it won't allow to set that value. How can I overcome this?
Private Sub OnRowUpdated(ByVal sender As Object, ByVal args As Data.OleDb.OleDbRowUpdatedEventArgs)
' Include a variable and a command to retrieve the identity value from the Access database.
Dim newID As Integer = 0
Dim idCMD As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT ##IDENTITY", args.Command.Connection(), args.Command.Transaction)
If args.StatementType = StatementType.Insert Then
' Retrieve the identity value and store it in the ProductIDNum column.
newID = CInt(idCMD.ExecuteScalar())
' place in the identity column of the local table in the dataset
'args.Row("ProdNum") = newID
End If
End Sub
I'm not sure whether you can do this using OleDb (you can't for Access, but that's a different OLE DB provider) but if you use SqlClient then there's no need to handle any events because you can simply tack a SELECTonto your INSERT in the CommandText of your adapter's InsertCommand, e.g.
INSERT INTO Thing (Name, Description) VALUES (#Name, #Description);
SELECT ThingId = SCOPE_IDENTITY();
That's always worked for me.

Insert date of new record into database using asp.net with VB

I'm working on a webapp project. I've added a function for the teacher to add exams. What I need is:
When the teacher adds a new exam record using a DetailsView, the date should be automatically inserted into the date columnn in the exams table in the database.
Here is the code :
Protected Sub DetailsView1_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles DetailsView1.ItemInserted
Dim conn As New SqlConnection()
conn.ConnectionString = ConfigurationManager.ConnectionStrings("MCQQUIZZES").ConnectionString
Dim sql As String = "INSERT INTO [Exams] VALUES(#Dateadded) "
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#Dateadded", Date.Now.ToString)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
the error massege :
Column name or number of supplied values does not match table definition.
any help??
Provide Column Names in Insert command
INSERT INTO Table(Col1, Col2) VALUES (value1,value2)
Please change the query in code.
INSERT INTO [Exams] (date) VALUES(getdate())

Insert X rows into child table based on parent field

Trying to insert a set number of rows into a child table based on a number entered into a parent table
parent (licenseID, poolSize)
child (nodeID, licenseID)
I was looking into using an After Insert trigger on the parent table but could not figure out how to loop a create record command.
Is this possible to do with macros or should I be looking at VBA code? (MS ACCESS 2010)
First of all, I would never enter anything directly into a table. Giving your users that kind of ability is always going to end up in some form of misery and regret.
I would creat a form to take the number, and then use code behind a "Submit" button to loop the required number of times. Something like (this code is entirely untested):
Dim db as Database
Dim rec as Recordset
Dim X as Double
Set db = CurrentDB
Set rec = db.OpenRecordset ("Child")
Do for X = 1 to Me.txtNumberOfEntries
rec.AddNew
rec("LicenseID") = me.txtLicenseID
rec.Update
Next X
'Always clear out your variables
Set rec = Nothing
Set db = Nothing

What's the best way to update a List on the database?

If I have the following list in C# that was loaded from the database
List<User> user = GetUsers(foo);
and it was updated and I want to store those changes in the database what's the best way of doing it using SQL? It should insert the records added to that list, updated the modified records and delete the ones that are not present in the collection.
I'm no using the EntityFramework so I need to do this using SQL.
Copy this list to datatable and set datatable RowStat as (modified,deleted,new)
and update datatable using sqldataadapter
Here's an example that adds or inserts a row. It searches for a row with a specific UserID. If the row exists, it uses update to grant the user a point. If the row does not exist, a new row is created with insert.
var connectionString = "Data Source=myServerAddress;" +
"Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
using (var con = new SqlConnection(connectionString))
{
con.Open();
var com = con.CreateCommand();
com.Parameters.AddWithValue("#UserId", userId);
com.CommandText = #"
if exists (select * from YourTable where UserId = #UserId)
update YourTable set TrollPoints = TrollPoints + 1 where UserId = #UserId
else
insert YourTable (UserId, TrollPoints) values (#UserId, 1)
";
com.ExecuteNonQuery();
}
The use of parameters allows the server to chache the execution plan, and also helps against SQL injection.