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.
Related
I am new to this forum.
I have the following environment: an Access frontend client that is connected to a database on SQL Server (backend). I would like to use an Access form to enter data that is associated with a specific ID number (in database Table). Ideally the ID will automatically increment when an INSERT is made to the Table. The vba code (based on the SQL query) I wrote is the following:
Option Compare Database
Option Explicit
Private Sub List0_Click()
Dim HelloWORLD As String
Dim dbsCurrent As Database
Set dbsCurrent = CurrentDb
CurrentDb.Execute "INSERT INTO Table1 (TESTING_1, TESTING_2) VALUES (" & 9 & "," & HelloWORLD & ")"
End Sub
The code is compiling but it is not appending the Table1 like it is supposed to do. Please Help.
You can use sequences.
You can creates sequence MySequence1 and use it:
CurrentDb.Execute "INSERT INTO Table1 (TESTING_1, TESTING_2) VALUES (NEXT VALUE FOR MyDemoSequence," & HelloWORLD & ")"
Can you make the ID field an IDENTITY field within SQL Server? This will automatically increment whenever a new row is inserted. Example from Microsoft documentation:
CREATE TABLE new_employees
(
id_num int IDENTITY(1,1),
fname varchar (20),
minit char(1),
lname varchar(30)
)
The first number is the seed, and the second is the increment, so IDENTITY(1,1) means start at '1', and increase by '1' each time.
You can retrieve the ID that was created using SELECT SCOPE_IDENTITY(); following the insert if necessary.
This is my table Produit(ID,libelle,prix). The ID is auto increment, and this is the insert instructions :
cmd.Connection = connexion
cmd.CommandText = "INSERT into Produit_fini(libelle,prix) values (#libelle,#prix)"
cmd.Parameters.AddWithValue("#libelle", libelle)
cmd.Parameters.AddWithValue("#prix", prix)
connexion.Open()
cmd.ExecuteNonQuery()
connexion.Close()
After executing that, an error is occured says that I can't insert NULL value to the ID !?
The column can not contain NULL values. [ Column name = ID,Table name
= Produit_fini ]
How can I insert the ID here ?
It seems like this column ID is not defined with an IDENTITY property. But, you won't be able to alter the table to add the IDENTITY property.
You have to delete the table (if there is no data on it), and create it again with the column ID has IDENTITY(1,1).
You might also need to use this tool Compactview to be able to run statements against SQL Server compact edition database.
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
Is it possible to list all triggers in all tables on a database?
I can list all user stored procedures with:
Private Sub StoredPro()
Dim theServer As Server = New Server(serverName)
Dim myDB As Database = theServer.Databases("mydatabase")
Dim dt As DataTable = myDB.EnumObjects(DatabaseObjectTypes.StoredProcedure)
End Sub
But nothing obvious in SMO for triggers. (I'm actually trying to list just custom triggers, any that are not named DEL_tablename, INS_tablename, UPD_tablename) within the selected database.
https://social.msdn.microsoft.com/forums/sqlserver/en-US/bb024fd6-c0b9-441a-864e-a579fc441267/list-databasetable-triggers-via-smo
A DatabaseDdlTrigger object represents a data definition language (DDL) trigger, which is created on a SQL Server database. However, from your description, I think you want to iterate over the data manipulation language (DML) triggers, which are created on SQL Server tables.
Please refer to the following sample:
Dim srv As New Server
Dim db As Database = srv.Databases.Item("Northwind")
Dim tb As Table
For Each tb In db.Tables
Dim trg As Trigger
For Each trg In tb.Triggers
If (((trg.Name <> ("INS_" & tb.Name)) AndAlso (trg.Name <> ("DEL_" & tb.Name))) AndAlso (trg.Name <> ("UPD_" & tb.Name))) Then
MessageBox.Show(trg.Name)
End If
Next
Next
Each database object has a Triggers property, which you can iterate to find all triggers.
Once you have a reference to this trigger, check the IsSystemObject property to check if it is a user-defined trigger or not.
foreach ( DatabaseDdlTrigger oTrigger in oDatabase.Triggers) {
if (! oTrigger.IsSystemObject) {
// do something
}}
Have fun.
I have an application that (currently) needs to uses DBs served by both SQL Server 2000 and SQL Server 2005.
I'm trying to move a DB programmatically from one server to the other. All of the tables I use each have a primary key that is autoincremented. Since these autoincremented keys are used as foreign keys in other tables, my plan of attack for copying the tables was to temporarily turn off the auto-increment on the destination table, INSERT the records verbatim (with the original primary keys) and then turn auto-increment back on.
If I understand correctly, I can "turn auto-increment on/off" one table at a time by executing
SET IDENTITY_INSERT tbl_Test ON;
...
SET IDENTITY_INSERT tbl_Test OFF;
My implementation is in VB 2005, using System.Data.SqlClient.
For brevity's sake, I'll only show the lines of code related to the construction of the SQL queries.
To create the table:
Dim createTableStatement As String = _
"CREATE TABLE tbl_Test (" & _
"ID_Test INTEGER PRIMARY KEY IDENTITY," & _
"TestData INTEGER" & _
")"
Dim createTableCommand As New SqlCommand(createTableStatement, connection)
createTableCommand.ExecuteNonQuery()
To turn IDENTITY_INSERT on or off:
Dim turnOffIdentInsertStatement As String = _
"SET IDENTITY_INSERT tbl_Test OFF;"
Dim turnOffIdentInsertCommand As New SqlCommand(turnOffIdentInsert, connection)
turnOffIdentInsertCommand.ExecuteNonQuery()
Dim turnOnIdentInsertStatement As String = _
"SET IDENTITY_INSERT tbl_Test ON;"
Dim turnOnIdentInsertCommand As New SqlCommand(turnOnIdentInsert, connection)
turnOnIdentInsertCommand.ExecuteNonQuery()
To insert a new record normally, without specifying primary key:
Dim insertRegularStatement As String = _
"INSERT INTO tbl_Test (TestData) VALUES (42);"
Dim insertRegularCommand As New SqlCommand(insertRegularStatement, connection)
insertRegularCommand.ExecuteNonQuery()
To insert a new record with an explicit primary key:
Dim insertWithIDStatement As String = _
"INSERT INTO tbl_Test (ID_Test, TestData) VALUES (20, 42);"
Dim insertWithIDCommand As New SqlCommand(insertWithIDStatement, connection)
insertWithIDCommand.ExecuteNonQuery()
So, my plan is to call the code that turns IDENTITY_ INSERT on, add the records with the explicit primary keys, then turn IDENTITY_ INSERT off.
This method appears to work fine when I'm talking to SQL Server 2000, but I run into an exception when I try the exact same code against SQL Server 2005:
"Cannot insert explicit value for identity column in table 'tbl_Test' when IDENTITY_INSERT is set to OFF."
Any hints? Thanks in advance as always.
It would be worth looking at SqlBulkCopy as it is optimized at importing bulk data.
Also worth looking into depending on the scenario would be to use an SSIS task to bulk copy the data (also uses the bulk copy API) or linked servers with a BULK INSERT statement (again, bulk copy API).
As for setting the identity are the set identity_insert statements executed on the same connection as the insert? As SQL Server 2005 only persists that setting on the current connection.
As the following worked fine for me on SQL Server 2008 Express:
using (var conn = CreateConnection())
{
conn.Open();
new SqlCommand("SET IDENTITY_INSERT Foo ON", conn).ExecuteNonQuery();
new SqlCommand("INSERT INTO Foo(id) VALUES (1)", conn).ExecuteNonQuery();
new SqlCommand("SET IDENTITY_INSERT Foo OFF", conn).ExecuteNonQuery();
}
You might have to insert a GO statement after your SET IDENTITY ... ON statement.
In a SQL query analyser session I would issue a GO after the IDENTITY_INSERT and before the actual insert. Maybe this applies to calling it from in code also?