0

I'm trying to insert data in my db. this is the code im using

SqlCommand cmd = new SqlCommand("dbo.UsersInsert", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@UserID", SqlDbType.Int);
cmd.Parameters.AddWithValue("@UserFirstName", FirstName.Text);
cmd.Parameters.AddWithValue("@UserMiddleName", MiddleName.Text);
cmd.Parameters.AddWithValue("@UserLastName", LastName.Text);

etc...

It is giving me error

Procedure or function 'UsersInsert' expects parameter '@UserID', which was not supplied.

on cmd.ExecuteNonQuery(); line.

Here, My UserID is auto-generated in my Database. How do I resolve this?

Stored Procedure

 @UserID INT OUTPUT,   
 @UserFirstName VARCHAR (50),  
 @UserMiddleName VARCHAR (50),  
 @UserLastName VARCHAR (50), etc... 

AS  
SET NOCOUNT ON  
DECLARE @ReturnValue int  
BEGIN  

 SELECT @ReturnValue = 0  

 INSERT [Users]  
 ( 
            [UserFirstName]
           ,[UserMiddleName]
           ,[UserLastName] etc... 
 values (

         @UserFirstName,  
                 @UserMiddleName,  
                 @UserLastName,  etc.. )
IF (@@Error <> 0) GOTO ERROR_HANDLER

 GOTO OnExit  
END  
4

2 回答 2

0

以下代码应该可以工作,更改sql以接受参数

SqlCommand cmd = new SqlCommand("dbo.UsersInsert @UserID out, @UserFirstName, @UserMiddleName, @UserLastName", cnn);

然后改变参数如下

var id = new SqlParameter("UserID", System.Data.SqlDbType.Int);
id.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(id);

cmd.Parameters.AddWithValue("UserFirstName", FirstName.Text);
cmd.Parameters.AddWithValue("UserMiddleName", MiddleName.Text);
cmd.Parameters.AddWithValue("UserLastName", LastName.Text);
于 2014-06-19T04:22:37.610 回答
0

你应该让它成为ParameterDirection.Output

SqlParameter userIdParam = new SqlParameter("@UserID", SqlDbType.Int);
userIdParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(userIdParam);

这样您就不必提供值

于 2013-09-27T10:59:52.170 回答