我正在執行存儲過程在c#(通過vs2008)使用ado.net與ExecuteScalar命令。存儲的proc返回輸入的新記錄的pkey,但ExecuteScalar返回null。我查看數據庫並確實添加了一條記錄。我可以使用輸出參數來獲取值,但我不知道爲什麼這不起作用。Ado.net ExecuteScalar()返回null
當我在ssms中執行sp時,會返回pkey。
我在做什麼錯?
下面是C#代碼:
public int SaveNewPerson(EPerson ePerson)
{
int newPersonPkey;
SqlConnection cn = new SqlConnection(cnn.PersonData);
using (cn)
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "People.dbo.AddNewPerson";
cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 150).Value = ePerson.LastName;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 150).Value = ePerson.FirstName;
cn.Open();
object result = cmd.ExecuteScalar();
newPersonPkey = int.Parse(result.ToString());
cn.Close();
}
catch (Exception e)
{
// call error method
throw new Exception(e.Message + " save new Person error ");
}
}
return newPersonPkey;
}
這是SP:
PROCEDURE [dbo].[AddNewPerson]
@FirstName varchar(50)
,@LastName varchar(50)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [People].[dbo].[Persons]
(
[FirstName]
,[LastName]
)
VALUES
(
@FirstName
,@LastName
)
declare @persons_PKey int
set @persons_PKey = @@IDENTITY
return @persons_PKey
end
當然!我以爲這已經奏效了。更改了return @persons_PKey以選擇@persons_PKey並且它工作正常。 – TheMoot 2010-12-09 16:29:14