Click here to Skip to main content
15,891,749 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I try to return single value to c# using executescalar method. When execute below stored procedure in sql server, if..blocks are working fine but executescalar in c# always returns 0.

please refer below code
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;
 }
Posted
Updated 6-May-15 4:49am
v3
Comments
MayurDighe 6-May-15 10:26am    
Show....how you use ExecuteScalar() function in your code.

1 solution

Just RETURN the value at the end. Replace
SQL
SELECT @Result As Result
With
SQL
RETURN @Result
 
Share this answer
 
Comments
Tomas Takac 6-May-15 10:51am    
I don't think this is correct. ExecuteScalar()[^] returns first column of the first row in the resultset and not the return value of the SP.
Member 9018012 6-May-15 10:52am    
Ok Thanks. I tried using ExecuteReader, It's working fine.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900