??如何使用企业库6获取存储过程返回值?

时间:2014-01-12 05:35:09

标签: sql stored-procedures return-value enterprise-library

---------- sproc code ----------------------------

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个多小时。

1 个答案:

答案 0 :(得分:0)

我偶然发现了你的问题,我也有同样的痛苦。

我已经尝试了帖子的建议,但它不起作用,并且在这方面的官方指导有限。

然而,作为一种解决方法,我已经开始工作了(砖块欢迎...-))

  1. 在sql而不是返回中,使用选择来返回值。所以在你的情况下这样做 if @initcount < (select count(*) from dbo.Customer) select max(CustomerID) from dbo.Customer else select 0 end

  2. 在c#中执行此操作

  3. if @initcount < (select count(*) from dbo.Customer) select max(CustomerID) from dbo.Customer else select 0 end

    希望它可以帮助您和其他企业库数据访问阻止用户。