Stored Procedure with IsIDenity and cmd.Parameters.Add
I am creating an ASP.NET Wiki for myself to track the knowlege I gain in C# and other language.
I have created a Stored Procedure to insert a category into a DB, the DB has two fields C_ID(int) and Category(varchar 25). In my ASP page, there is no field for C_ID, it increments automatically by IsIdentiy = true;
开发者_如何学编程When I try to excute it, it fails. What is the best approach to handle this?
Code:
ALTER PROCEDURE dbo.InsertCategory
@ID int,
@CATEGORY varchar(25)
AS
INSERT INTO Wiki
(C_ID, C_Category)
Values (@ID, @CATEGORY)
/* SET NOCOUNT ON */
RETURN
Did I miss something to insert from the .aspx page? try {
//create a command object identifying the Stored Procedure
SqlCommand cmd = new SqlCommand("InsertCategory", conn);
//Set the command type
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("Category", txtAddCatagory));
cmd.ExecuteNonQuery();
}
Just omit the id
from the insert. If you configured identity
correctly, the database will take care of increasing the number. For example:
GO
ALTER PROCEDURE dbo.InsertCategory(@CATEGORY varchar(25))
AS
INSERT INTO Wiki (C_Category) Values (@CATEGORY)
GO
To verify the identity
is set correctly, if you script the table, the C_id
column should look like;
[C_id] [int] IDENTITY(1,1) NOT NULL,
Or even better:
[C_id] [int] IDENTITY(1,1) PRIMARY KEY,
So you're getting an exception that you cannot insert into an identity column, right? The trick is to not specify the identity column in your insert statement, because it automatically get populated... ;)
ALTER PROCEDURE dbo.InsertCategory @CATEGORY varchar(25) AS
INSERT INTO Wiki (C_Category) Values (@CATEGORY) /* SET NOCOUNT ON */ RETURN
精彩评论