我知道这个问题很老...但是您可以使用输出参数获取插入的记录 ID。
这是我有一个存储过程的例子
IF object_id('spOrganizationAdd') IS NOT NULL
DROP PROCEDURE spOrganizationAdd;
GO
CREATE PROCEDURE dbo.spOrganizationAdd
@OrganizationName VARCHAR(50),
@ReturnIdentityValue INT OUTPUT
AS
BEGIN
DECLARE @TempOrganizationIdentity TABLE (TempOrganizationID INT)
INSERT INTO Organization (OrganizationName)
OUTPUT INSERTED.OrganizationID INTO @TempOrganizationIdentity
VALUES (@OrganizationName)
SELECT @ReturnIdentityValue = (SElECT TempOrganizationID FROM @TempOrganizationIdentity)
END
GO
这是调用它的 C# 代码示例...注意ParameterDirection.Output
:
public static int AddOrganization(Organization oOrganization)
{
int iRetVal = 0;
using (SqlConnection conn = Connection.GetConnection())
{
using (SqlCommand cmd = new SqlCommand("spOrganizationAdd", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@OrganizationName", oOrganization.OrganizationName);
cmd.Parameters.Add("@ReturnIdentityValue", SqlDbType.Int).Direction = ParameterDirection.Output;
conn.Open();
cmd.ExecuteNonQuery();
iRetVal = Convert.ToInt32(cmd.Parameters["@ReturnIdentityValue"].Value);
}
}
return iRetVal;
}
类示例
public class Organization
{
public Organization() { }
public Organization(int organizationID) { OrganizationID = organizationID; }
public int OrganizationID { get; set; }
public string OrganizationName { get; set; }
public string Display()
{
return OrganizationID.ToString() + " " + OrganizationName;
}
}