Ms Sql Stored Procedured选择值

时间:2014-04-17 07:19:53

标签: sql sql-server stored-procedures

存储过程:

ALTER procedure [dbo].[StockEnumerationDetailGetFindProduct]

       @StockEnumerationMasterId BIGINT,
       @ProductId BIGINT

    as


    DECLARE @Remaining float
    DECLARE @WarehouseStock float
    DECLARE @WarehouseCode nvarchar(10)


begin

    set @WarehouseCode= 
    (
    Select w.Code  from [dbo].StockEnumerationMaster as SEM
    INNER JOIN [dbo].Warehouses as w on w.[Id]=SEM.WarehouseId
    where
    SEM.Id=@StockEnumerationMasterId)

    set @WarehouseStock=dbo.FncWareHouseStockControl(@WarehouseCode,@ProductId)



    select @WarehouseStock

end

选择@WarehouseStock在代码端不起作用。

我的代码:

 public IList<FormEnumerationDetailModel> StockEnumerationDetailGetFindProduct(long stockEnumerationMasterId, long productId)
        {
            using (var connection = new SqlConnection(Properties.Resources.ConnectionString))
            {
                var command = new SqlCommand(Properties.Resources.StockEnumerationDetailGetFindProduct, connection);
                var formEnumerationDetailModel = new List<FormEnumerationDetailModel>();
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@StockEnumerationMasterId", stockEnumerationMasterId);
                command.Parameters.AddWithValue("@ProductId", productId);
                try
                {
                    connection.Open();
                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        formEnumerationDetailModel.Add(new FormEnumerationDetailModel()
                        {
                            Unit = float.Parse(reader["WarehouseStock"].ToString())
                        });
                    }
                    connection.Close();
                    return formEnumerationDetailModel;
                }
                catch (Exception e)
                {
                    return new List<FormEnumerationDetailModel>();
                }
            }
            return new List<FormEnumerationDetailModel>();
        }

例外:

{&#34; WarehouseStock&#34;}

为什么例外只会显示我&#34; {&#34; WarehouseStock&#34;}&#34; ?

如果我在ms sql上运行存储过程,它可以工作。

但是,如果我在代码端运行存储过程,它会给出&#34; {&#34; WarehouseStock&#34;}&#34;异常。

我到底错过了什么?

我们将不胜感激。

感谢。

2 个答案:

答案 0 :(得分:1)

将过程中的select @WarehouseStock行更改为select @WarehouseStock as WarehouseStock

答案 1 :(得分:0)

当你知道存储的proc只返回一个值时,你可以使用ExecuteScalar而不是使用ExecuteReader并循环遍历单个结果。

connection.Open();
var unit = (float)command.ExecuteScalar();
connection.Close();
formEnumerationDetailModel.Add(new FormEnumerationDetailModel()
         {
             Unit = unit
         });