Tuesday, March 27, 2012

Help with c# syntax

Hello,

I have at sp that return a value:
setANSI_NULLSON

setQUOTED_IDENTIFIERON

go

ALTERPROCEDURE [dbo].[sp_getLastActivityDate]

(

@.useridnvarchar(256)

)

AS

DECLARE @.retnvarchar(256)

SET @.ret=(SELECTCAST(LastActivityDateASnvarchar)

FROM aspnet_Users

WHERE UserName= @.userid)

RETURN @.ret

The sp returns a nvarchar. How can i write the syntax in C# to grab the value in @.ret?

// Tomas

I tried to make a very simple try to retrieve the value from sp but I get exception

"String[0]: the Size property has an invalid size of 0." exception

Whats wrong with this code?

ALTERPROCEDURE [dbo].[sp_test1]
(
@.UNnvarchar='AHHHH'OUTPUT
)
as

and the c# code

using (SqlConnection connection =newSqlConnection(ConfigurationManager.ConnectionStrings["nyconn"].ConnectionString))

{

using (SqlCommand command =newSqlCommand("sp_test1", connection))

{

command.CommandType =CommandType.StoredProcedure;

SqlParameter para = command.Parameters.Add("@.UN",SqlDbType.NVarChar);

para.Direction =ParameterDirection.Output;

connection.Open();

command.ExecuteNonQuery();

string s = (String)command.Parameters["@.UN"].Value;

connnection.Close();|||

Hi,

From your second post, it seems that you are using SqlCommand to execute your stored procedure and declare a output parameter to retrieve the return from your stored procedure, right?

If so, the cause of getting errors like ""String[0]: the Size property has an invalid size of 0." exception" is that you didn't set the size of the output parameter. Since you are declaring an output parameter, it's necessary to declare the size of the parameter explicitly in your code. See the following code snippet:

SqlParameter para = command.Parameters.Add("@.UN", SqlDbType.NVarChar);
para.Direction = ParameterDirection.Output;
para.Size = 50; // 50 for example.

Thanks.

No comments:

Post a Comment