当存储过程返回值

时间:2015-05-06 13:47:09

标签: c# sql-server

我正在尝试使用executescalar方法将单个值返回给c#。

当我在SQL Server中执行以下存储过程时,if..blocks工作正常,但c#中的executescalar始终返回0

请参阅以下代码:

USE [xx]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[prcAddress]
    @ID int, 
    @Name varchar(50),
    @Designation varchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @count as Integer -- To count records
    Declare @Result int -- To return result

    SELECT @Result=0
    SELECT @count = (SELECT count(*) FROM dbo.Address)

    IF @ID >0
    BEGIN
    --Update the current entry
    SELECT @Result=1
    END
    ELSE IF @ID =0 AND @count=0
    BEGIN
        -----do something
    SELECT @Result=2
    END
    ELSE IF @ID=0 AND @count>0
    BEGIN
    ----do something
    SELECT @Result=3
    END
    ELSE
    BEGIN
    SELECT @Result=4
    END

    SELECT @Result As Result
END
GO

           SqlConnection sqlCon = new SqlConnection(ConnectionString);
            SqlCommand sqlCom = new SqlCommand();

            try
            {
                sqlCom = new SqlCommand("prcAddress", sqlCon);
                sqlCom.CommandType = CommandType.StoredProcedure;
                sqlCom.CommandTimeout = 15;
                sqlCom.Connection = sqlCon;
                foreach (KeyValuePair<Object, Object> parmater in parameters)
                {
                    if (parmater.GetType() == typeof(DateTime))
                    {
                        sqlCom.Parameters.Add("@" + parmater.Key, SqlDbType.DateTime).Value = parmater.Value;
                    }
                    else
                    {
                        sqlCom.Parameters.AddWithValue("@" + parmater.Key, parmater.Value);
                    }
                }

                if (sqlCon.State != ConnectionState.Closed)
                {
                    sqlCon.Close();
                }
                sqlCon.Open();
                if (sqlCom.ExecuteScalar() != null)
                {
                    result = sqlCom.ExecuteScalar().ToString();
                }
                else
                {
                    result = "";
                }
            }
            catch (SqlException sqlEx)
            {
                System.Web.HttpContext.Current.Response.Redirect("~/Error.aspx", false);
            }
            finally
            {
                sqlCon.Close();
                sqlCom = null;
            }

1 个答案:

答案 0 :(得分:1)

您可能会看到第一个选择的结果,'SELECT @ Result = 0'。在存储过程中的最后一次选择之前注释掉所有选择,或者将其更改为返回结果的标量函数。