Monday, March 12, 2012

Retrieving data using a stored procedure

I have created the following stored procedure and tried to retrieve it's output value in C#, however I am getting exceptions. Can anyone tell me what I am doing wrong? Thanks!

1 ALTER PROCEDURE [dbo].[GetCustomerById]23@.CustId NCHAR(5),4@.CustomerName NVARCHAR(50) OUTPUT56 AS7 BEGIN89SELECT @.CustomerName = ContactName10FROM Customers11WHERE CustomerId = @.CustId1213 END1415 RETURN16171819202122 SqlConnection conn = GetConnection();//retrieves a new SqlConnection23 SqlCommand cmd =new SqlCommand();24 cmd.Connection = conn;25 cmd.CommandType = CommandType.StoredProcedure;26 cmd.CommandText ="GetCustomerById";2728 SqlParameter paramCustId =new SqlParameter();29 paramCustId.ParameterName ="@.CustId";30 paramCustId.SqlDbType = SqlDbType.NChar;31 paramCustId.Direction = ParameterDirection.Input;32 paramCustId.Value ="ALFKI";3334 SqlParameter paramCustomerName =new SqlParameter();35 paramCustomerName.ParameterName ="@.CustomerName";36 paramCustomerName.SqlDbType = SqlDbType.NVarChar;37 paramCustomerName.Direction = ParameterDirection.Output;3839 cmd.Parameters.Add(paramReturn);40 cmd.Parameters.Add(paramCustId);41 cmd.Parameters.Add(paramCustomerName);4243 conn.Open();44 SqlDataReader reader = cmd.ExecuteReader();4546string custName = cmd.Parameters["@.CustomerName"].Value.ToString();

You are not specifying the size, try

cmd.Parameters.Add("@.CusomerId", SqlDbType.NVarChar, 5);
cmd.Parameters["@.CustomerName"].Value ="ALFKI";
cmd.Parameters.Add("@.CustomerName", SqlDbType.NVarChar, 50);
cmd.Parameters["@.CustomerName"].Direction = ParameterDirection.Output;

|||I tried that. Still no luck.|||Try writing
ParameterDirection.Returninstead ofParameterDirection.Output
and since the stored Procedure is returning only 1 value.... you can try using ExecuteScaler instead of ExecuteReader.......|||Please post the full text of your error message.|||Does your stored proc return the value when you run it in the query analyzer? Also try changing your @.CustID to nvarchar instead of nchar. char is fixed length so if the value you are passing is < the specified length SQL Server will padd it with spaces to make it the fixed with. So if you pass in CustID of C123 it will become @.CustID = 'C123 '|||

I should have written

http://forums.asp.net/thread/1631113.aspx

cmd.Parameters.Add("@.CusomerId", SqlDbType.NChar, 5);
cmd.Parameters["@.CustomerName"].Value ="ALFKI";
cmd.Parameters.Add("@.CustomerName", SqlDbType.NVarChar, 50);
cmd.Parameters["@.CustomerName"].Direction = ParameterDirection.Output;

No comments:

Post a Comment