Hi i’m having trouble with inserting incremented userid inside my db below is my table,stored proc,and my code.
CREATE TABLE [dbo].[Assignment2]
(
userID int PRIMARY KEY IDENTITY(1,1),
Name varchar(255) NOT NULL,
Age int NOT NULL,
Hobbies varchar(255)
)
and a stored procedure
ALTER PROCEDURE [db].[p_Assignment2_ins]
@userID int,
@Name nvarchar(100),
@Age int,
@Hobbies nvarchar(100)
AS
INSERT INTO [DB].[db].[Assignment2]
([Name]
,[Age]
,[Hobbies])
VALUES
(@Name
,@Age
,@Hobbies)
If @@Error <> 0
Return -1
Select @userID = @@Identity // this one just get the latest id that we inserted right?
Return 0
I have some question :
-
I want to know how do we insert the
UserIDfrom the code behind because If the table is empty at first shouldn’t we insert a data first into the table -
How do we generate an
AutoIncrementIDfrom codebehind and insert itSqlConnection conn = new SqlConnection(ts.ConnMethod()); SqlCommand cmd = new SqlCommand("p_Assignment2_ins", conn); cmd.CommandType = CommandType.StoredProcedure; //I'm missing how we should add the IncrementedID cmd.Parameters.AddWithValue("@Name", TextBox1.Text); cmd.Parameters.AddWithValue("@Age", TextBox2.Text); cmd.Parameters.AddWithValue("@Hobbies", TextBox3.Text); conn.Open(); cmd.ExecuteNonQuery(); conn.Close();
Any help is really appreciated thanks
If you have AUTOINCREMENT field, you SHOULD NOT insert and generate values at all. DB is doing all by itself. So, remove the code that inserts ID-s