Insert primary key to other tables using VB.NET - sql

I'm using SQL Server as my DBMS and I have 2 tables namely Person and Voter.
Person has these columns:
PersonId (int, primary key auto-increment int_identity),
FirstName (nvarchar(50))
LastName (nvarchar(50))
Voter has these columns:
VoterPersonId (int, foreign key)
VoterPlace (nvarchar(50))
These 2 tables are related. For 1 person there can only be 1 voter place. So you may call it a one is to one relationship. I created 2 tables because there are also people who aren't voters that I must include in my database and I don't want to create null values so I made a separate table which is the 'voter' table. Basically, I wanted to know the number registered voters and non-voters in our city. Now, I have created a 'save' button in VB.NET and used the following code to insert information into my tables:
Dim sql As New SQLControl
Private Sub cmdSave_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
sql.con.Open()
Using cmdPerson As New SqlClient.SqlCommand("INSERT INTO Person(FirstName, LastName) VALUES('" & txtFirstName.Text & "', '" & txtLastName.Text & "')", sql.con)
cmdPerson.ExecuteNonQuery()
End Using
Using cmdVoter As New SqlClient.SqlCommand("INSERT INTO Voter(VoterPlace) VALUES('" & txtVoterPlace.Text & "')", sql.con)
cmdVoter.ExecuteNonQuery()
End Using
sql.con.Close()
End Sub
Now, my problem is I don't know how to transfer the value of 'PersonId' primary key which is auto-increment in_identity into 'VoterPersonId' the moment I click on the 'save' button. Is it possible? Can you please help me on this matter? I would really appreciate it.

You can execute both queries in a single stored procedure
CREATE PROCEDURE InsertPerson
#firstname varchar(50),
#lastname varchar(50),
#voterPlace varchar(50)
AS
declare #newid int
INSERT INTO Person(Firstname, Lastname) VALUES (#firstname, #lastname)
SELECT #newid = SCOPE_IDENTITY()
INSERT INTO Voter(VoterPersonId, VoterPlace) VALUES ( #newid, #voterPlace)

You can use a stored procedure but you certainly don't have to. The principle is still the same though. You execute the insert to the parent table and then use the SCOPE_IDENTITY function to get the auto-generated ID. You would then use an output parameter to get that value back into your app so that you can include it in the next insert to the child table, e.g.
Using connection As New SqlConnection("connection string here"),
parentCommand As New SqlCommand("INSERT INTO Parent (ParentName) VALUES (#ParentName); SET #ParentId = SCOPE_IDENTITY();", connection),
childCommand As New SqlCommand("INSERT INTO Child (ParentId, ChildName) VALUES (#ParentId, #ChildName)", connection)
With parentCommand.Parameters
.AddWithValue("#ParentName", parentName)
.Add("#ParentId", SqlDbType.Int).Direction = ParameterDirection.Output
End With
connection.Open()
Dim transaction = connection.BeginTransaction()
Try
parentCommand.ExecuteNonQuery()
With childCommand.Parameters
.AddWithValue("#ParentId", parentCommand.Parameters("#ParentId").Value)
.AddWithValue("#ChildName", childName)
End With
childCommand.ExecuteNonQuery()
transaction.Commit()
Catch
transaction.Rollback()
End Try
End Using

Related

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())

vb.net foreign key insert sql statement

I have encounter a problem where it tell me I have an Invalid SQL statement; expected 'DELETE','INSERT','PROCEDURE', 'SELECT', or 'UPDATE'.
I am trying to insert data that use foreign key.
Table pemain contain
ID
MABOPA
PKBM
MBA
MBEIA
PPPBBM
MAPIM
Table Ahli contain
ID
company_name
name
address
poscode
state
email
phone
fax
company_reg
website
remarks
pemain
where field pemain in table Ahli is the foreign key of table pemain
the code im using are
Dim Pos As Integer
Dim Pemain As Integer
Int32.TryParse(TxtBoxPoscode.Text, Pos)
Int32.TryParse(TxtBoxPemainId.Text, Pemain)
Access.AddParam("#MABOPA", TextBox1.Text)
Access.AddParam("#PKBM", TextBox2.Text)
Access.AddParam("#MBA", TextBox3.Text)
Access.AddParam("#MBEIA", TextBox4.Text)
Access.AddParam("#PPPBBM", TextBox5.Text)
Access.AddParam("#MAPIM", TextBox6.Text)
Access.AddParam("#companyname", TxtBoxComName.Text)
Access.AddParam("#name", TxtBoxName.Text)
Access.AddParam("#address", TxtBoxAdd.Text)
Access.AddParam("#poscode", Pos)
Access.AddParam("#state", CboBoxState.Text)
Access.AddParam("#email", TxtBoxEmail.Text)
Access.AddParam("#phone", TxtBoxPhone.Text)
Access.AddParam("#fax", TxtBoxFax.Text)
Access.AddParam("#companyreg", TxtBoxComName.Text)
Access.AddParam("#web", TxtBoxWebsite.Text)
Access.AddParam("#remarks", TxtBoxRemarks.Text)
Access.AddParam("#pemain", Pemain)
'Execute Insert Command
Access.ExecQuery(
"START TRANSACTION;" & _
"INSERT INTO pemain (MABOPA, PKBM, MBA, MBEIA, PPPBBM, MAPIM);" & _
"VALUES (#MABOPA, #PKBM, #MBA, #MBEIA, #PPPBBM, #MAPIM);" & _
"DECLARE #NewID INT;" & _
"SELECT #NewID = SCOPE_IDENTITY();" & _
"INSERT INTO Ahli (company_name, name, address, poscode, state, email, phone, fax, company_reg, website, remarks, pemain);" & _
"VALUES (#companyname, #name, #address, #poscode, #state, #email, #phone, #fax, #companyreg, #web, #remarks, #NewID);" & _
"COMMIT;")
It would be a really great if anyone could help me.
Neither the Jet nor ACE OLE DB providers support multiple SQL statements per command. If you want to execute multiple SQL statements then you must execute multiple commands (or the same command more than once with different SQL statements) and if you want to wrap them in a transaction then you call BeginTransaction on your OleDbConnection to create an OleDbTransaction.
By the way, I'm not sure that SCOPE_IDENTITY exists in Access. I could be wrong but I think that that's specific to SQL Server. I think Access requires using ##IDENTITY.

How to increment ID by 1 in SQL Server (backend) when INSERT code is written in vba (frontend)?

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.

Updating Value in SQL Server using MS Access Using VB.Net Programming

I have a critical requirement , need to update a table in Sql server from access through forms and buttons,
When a user clicks the button in the form he should be able to update the record which is already existing in the database.
For Eg: table has columns -EmployeeID , Employee Name, Employee Location
EmployeeID Values
-----
1001|
2301|
3212|
Suppose a user wants to update value of EmployeeName alone not employee location ,he should be able to do that in some case employee.
update table set EmployeeName=#New_employee_name , Employee Location=#New_employee_location where EmployeeID=#Employee_ID
This should be driven through vb. net program inorder to update the user input value in the database.
I would recommend you create a Stored Procedure on the SQL Server, here is an example:
CREATE PROCEDURE sp_UpdateEmployeeByID
(
#ID int,
#TitleID int,
#FirstName nvarchar(255),
#LastName nvarchar(255)
)
AS
BEGIN
SET NOCOUNT ON;
UPDATE Employee SET
TitleID = #TitleID,
FirstName = #FirstName,
LastName = #LastName
WHERE ID = #ID
END
Using stored procedures rather than ad-hoc SQL protects you from SQL Injection attacks plus there are performance benefits.
Then using VB.Net you will want to call the Stored Procedure, passing in the updated employee values.
Public Sub UpdateEmployeeByID(Byval ID As Int32, Byval TitleID As Int32, Byval FirstName As string, Byval LastName As string)
Dim connString As String = ConfigurationManager.AppSettings("ConnectionString")
Dim conn As New SqlConnection(connString)
conn.Open()
Dim sqlCommand As new SqlClient.SqlCommand("sp_UpdateEmployeeByID", conn)
sqlCommand.CommandType = CommandType.StoredProcedure
sqlCommand.Parameters.AddWithValue("#ID", ID)
sqlCommand.Parameters.AddWithValue("#TitleID", TitleID)
sqlCommand.Parameters.AddWithValue("#FirstName", FirstName)
sqlCommand.Parameters.AddWithValue("#LastName", LastName)
Try
sqlCommand.ExecuteNonQuery()
Catch ex As SqlException
'Handle SQL exceptions
Catch ex As Exception
'Handle exceptions
Finally
'clean up resources that access Data
If IsNothing(sqlCommand) = False Then
sqlCommand.Dispose()
sqlCommand = Nothing
End If
conn.Close()
End Try
End Sub