----------存儲過程的代碼----------------------------??如何使用企業庫6獲取存儲過程返回值?
CREATE proc dbo.[usp_UpsertCustomer]
@CustomerID int, @CustomerName nvarchar(50), @CustomerAddress nvarchar(100),
@CustomerPhone nvarchar(50), @CustomerEmail nvarchar(50)
as
set nocount on
declare @initcount int = (select count(*) from dbo.Customer)
begin
merge dbo.Customer as c
using (select @CustomerID,@CustomerName,@CustomerAddress,@CustomerPhone,@CustomerEmail) as s
-- src data maps to the following fields
(CustomerID, CustomerName, CustomerAddress, CustomerPhone, CustomerEmail)
on c.CustomerID = s.CustomerID
when matched then --update the record
update set c.CustomerName = s.CustomerName, c.CustomerAddress = s.CustomerAddress,
c.CustomerPhone = s.CustomerPhone, c.CustomerEmail = s.CustomerEmail
when not matched then --insert the new record
insert (CustomerName,CustomerAddress,CustomerPhone,CustomerEmail)
values (s.CustomerName,s.CustomerAddress,s.CustomerPhone,s.CustomerEmail);
-- return ID of the new record if created
if @initcount < (select count(*) from dbo.Customer)
return (select max(CustomerID) from dbo.Customer)
else
return 0
end
- -------- c#code -------------------------
public class clsAutoInvoiceDb
{
private Database objDb = new DatabaseProviderFactory().CreateDefault();
public int CreateCustomer(string _CustomerName, string _CustomerAddress,
string _CustomerPhone, string _CustomerEmail)
{
DbCommand cmd = objDb.GetStoredProcCommand("usp_UpsertCustomer");
objDb.AddParameter(cmd, "@return_value", DbType.Int32, ParameterDirection.ReturnValue, null, DataRowVersion.Default, null);
objDb.ExecuteNonQuery("usp_UpsertCustomer", -1, _CustomerName, _CustomerAddress, _CustomerPhone, _CustomerEmail);
return Convert.ToInt32(objDb.GetParameterValue(cmd, "@return_value"));
-------- - 我的問題/問題-----------------
insert總是成功的,但執行return語句時@return_value爲null。在重構使用entlib之前,這段代碼段的生活很好。現在無法獲得我的返回值。有人有主意嗎?已經浪費了3個多小時。
我可以看到你的sproc有一些問題,「工作」與否。 –
請賜教。着名的是,sproc「在我的機器上正常工作。」問題在於objDb.ExecuteNonQuery。當我使用(sprocname + params [])重載時,return_value永遠不會使用CustomerID填充。當我使用objDb.ExecuteNonQuery(cmd)時,工作正常。但是,使用...(cmd)需要使用objDb.AddInParameter逐個添加參數值。我更喜歡1行...(sproc,params [])重載,但唉,不會返回return_value –