我期待將一行插入到表中並返回c#代碼中的標識列。我似乎無法得到正確的語法。如何從C#代碼中的SQL Server過程返回標識列
這裏是storted過程
ALTER PROCEDURE [dbo].[sp_InsertIssue]
@Application nchar(20) = NULL ,
@Version nchar(10) = NULL ,
@CreatedBy NVARCHAR(30) = NULL ,
@AssignedTo nVARCHAR(max) = NULL ,
@Description nVARCHAR(max) = NULL ,
@UserId INT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.Issue
(
Application ,
Version ,
CreatedBy ,
AssignedTo ,
Description ,
UserId
)
VALUES
(
@Application ,
@Version ,
@CreatedBy ,
@AssignedTo ,
@Description ,
@UserId
)
RETURN SCOPE_IDENTITY()
END
這裏是C#代碼
的SqlCommand CMD =新的SqlCommand();更仔細地閱讀你的代碼後
cmd.CommandText = "sp_InsertIssue ";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection = m_Connection;
SqlParameter parm = new SqlParameter("@IssueId", SqlDbType.Int);
parm.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add("@Application", SqlDbType.VarChar).Value = p_Application;
cmd.Parameters.Add("@Version", SqlDbType.VarChar).Value = p_Version;
cmd.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = p_CreatedBy;
cmd.Parameters.Add("@AssignedTo", SqlDbType.VarChar).Value = p_AssignedTo;
cmd.Parameters.Add("@Description", SqlDbType.VarChar).Value = p_Description;
cmd.Parameters.Add("@UserId", SqlDbType.Int).Value = p_UserId;
var returnParameter = cmd.Parameters.Add("IssueId", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
/// send data to db
Int32 id = (int)cmd.ExecuteNonQuery();
返回-1不是標識列
http://stackoverflow.com/questions/13416811/fetch-scope-identity-value-in-c-sharp-code-from-stored-procedure-in-3-tier-archi –
兩個問題在這裏。首先你不應該使用返回值來返回數據。它旨在返回執行狀態。您應該使用OUTPUT參數。第二個問題是sp_前綴。您應該將前綴更改爲其他內容,或者甚至更好地完全刪除前綴。 http://sqlperformance.com/2012/10/t-sql-queries/sp_prefix –