2012-10-14 8 views
5

出力パラメータを使用してデータベースから値を取得しています。C#関数のストアドプロシージャから複数の出力パラメータを返す方法

は、これは私のストアドプロシージャです:私は最後に戻っについてはよく分からない

ALTER PROCEDURE [dbo].[sp_GetCustomerMainData] 
    -- Add the parameters for the stored procedure here 
     @Reference nvarchar(100), 
     @SubscriptionPIN nvarchar(100) OUTPUT, 
     @SignupDate nvarchar(100) OUTPUT, 
     @ProductCount int OUTPUT 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 

    SET @SubscriptionPIN = 'N/A' 
    SET @SignupDate = 'N/A' 
    SET @ProductCount = 0 

    -- Insert statements for procedure here 
    IF EXISTS(SELECT [SubscriptionPIN] FROM [Norton].[dbo].[Customers] WHERE [Reference] = @Reference) 
    BEGIN 
     SELECT TOP 1 @SubscriptionPIN = [SubscriptionPIN], @SignupDate = SignUpDate FROM [Norton].[dbo].[ProductList] WHERE [Reference] = @Reference 
     SET @ProductCount = (SELECT COUNT(*) FROM [Norton].[dbo].[ProductList] WHERE [Reference] = @Reference) 
    END 

    RETURN (@SubscriptionPIN) 
    RETURN (@SignupDate) 
    RETURN (@ProductCount) 
END 

:他の側では

RETURN (@SubscriptionPIN) 
RETURN (@SignupDate) 
RETURN (@ProductCount) 

、ここではC#のコードです

using (SqlConnection con = new SqlConnection(connectionInfo)) 
{ 
    using (SqlCommand cmd = new SqlCommand("sp_GetCustomerMainData", con) { CommandType = CommandType.StoredProcedure }) 
    { 
     cmd.Parameters.Add("@Reference", SqlDbType.NVarChar).Value = CustomerReferenceID; 

     SqlParameter SubscriptionPIN = new SqlParameter("@TheCustomerID", SqlDbType.NVarChar) { Direction = ParameterDirection.Output }; 
     cmd.Parameters.Add(SubscriptionPIN); 

     SqlParameter SignupDate = new SqlParameter("@SignupDate", SqlDbType.NVarChar) { Direction = ParameterDirection.Output }; 
     cmd.Parameters.Add(SignupDate); 

     SqlParameter ProductCount = new SqlParameter("@ProductCount", SqlDbType.Int) { Direction = ParameterDirection.Output }; 
     cmd.Parameters.Add(ProductCount); 

     con.Open(); 

     try 
     { 
      cmd.ExecuteNonQuery(); 

      if (cmd.Parameters["@TheCustomerID"].Value.ToString() != "N/A") 
      { 
       aStatus.SubscriptionPIN = cmd.Parameters["@TheCustomerID"].Value.ToString(); 
       aStatus.SignupDate = cmd.Parameters["@SignupDate"].Value.ToString(); 
       aStatus.ProductCount = int.Parse(cmd.Parameters["@ProductCount"].Value.ToString()); 
       aStatus.Result = "0: Reference ID Found"; 
      } 
      else 
      { 
       aStatus.Result = "1: Reference ID does not exists"; 
       return aStatus; 
      } 
      } 
      catch (SqlException sqlExc) 
      { 
       foreach (SqlError error in sqlExc.Errors) 
       { 
        aStatus.Result = string.Format("{0}: {1}", error.Number, error.Message); 
        return aStatus; 
       } 
      } 
     } 
} 

このコードを実行すると、エラーが発生します。

System.InvalidOperationException: String[1]: the Size property has an invalid size of 0.
at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc)
at System.Data.SqlClient.SqlCommand.SetUpRPCParameters(_SqlRPC rpc, Int32 startCount, Boolean inSchema, SqlParameterCollection parameters)
at System.Data.SqlClient.SqlCommand.BuildRPC(Boolean inSchema, SqlParameterCollection parameters, _SqlRPC& rpc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

ストアドプロシージャから多くの出力パラメータを送信する正しい方法は何か分かりませんが、誰かが助けてくれますか?

+1

あなたがちょうどプロシージャ内でそれらに値を代入し、出力パラメータの 'RETURN'を使用しないでください。 'ProductList WHERE Reference = @ Reference'に一致する行が複数ある場合(つまり、' @ ProductCount'が '> 1 'の場合)、' @SubscriptionPIN、@ SignupDate'に割り当てるときにどの行が使用されるのかは不確定です。また、['SqlParameter(String、SqlDbType、Int32)'](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter)を使用する必要があるように見えるエラーメッセージから、 .aspx) –

+0

Martinさん、最初はあなたの返事を気付かなかったけれど、とても役に立ちました。 – Yasser

答えて

1

あなたはnvarcharパラメータの最大長を指定する必要があります。

SqlParameter SubscriptionPIN = new SqlParameter("@TheCustomerID", SqlDbType.NVarChar, 100) { Direction = ParameterDirection.Output }; 
cmd.Parameters.Add(SubscriptionPIN); 
SqlParameter SignupDate = new SqlParameter("@SignupDate", SqlDbType.NVarChar, 100) { Direction = ParameterDirection.Output }; 
cmd.Parameters.Add(SignupDate); 

ストアドプロシージャからreturn文を削除します。返される出力パラメータについては、何もする必要はありません。 (また、あなただけの1つのreturnステートメントを使用することができ、あなたは整数値のみを返すことができます。あなたはその戻り値を取得する方向ReturnValueでパラメータを使用します。)

ここ
+0

ありがとうございました。私の問題を解決しました。 – Yasser

2

最初のRETURNの後にプロシージャの実行が終了します。「クエリまたはプロシージャから無条件に終了します。

は手順の終わりに

SELECT @SubscriptionPIN AS SubsPIN , @SignupDate AS SignUpDate, @ProductCount AS ProdCount 

で1つのレコードとして、両方の値を返すことを検討してください。

+0

あなたの答えをありがとう、私はそれを変更するが、私はまだ実行時にエラーが発生する、C#コードの変更が行われる必要がありますか? – Yasser

0

があり、私が試したものを、それが罰金

に取り組んでいます
**Stored Procedures** 

STORED PROCEDURE 1 

create procedure spLoginCount 
@userid nvarchar(50), 
@password nvarchar(50), 
@count int out 
as 
Begin 
    select @count=count(userid) from users where [email protected] and [email protected] 
End 



**STORED PROCEDURE 2** 

create procedure spLoginData 
@userid nvarchar(50), 
@usertype nvarchar(20) out, 
@lastlogin nvarchar(100) out 
as 
Begin 
    select @usertype=usertype,@lastlogin=lastlogin from users where [email protected] 
End 


**ASP.NET code which will get values of two output Parameters**.... 



protected void btnLogin_Click(object sender, EventArgs e) 
    { 
     string uid="", psw=""; 
     uid = txtUserName.Text; 
     psw = txtPassword.Text; 

     string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; 
     using (SqlConnection scon = new SqlConnection(cs)) 
     { 
      SqlCommand scmd = new SqlCommand("spLoginCount", scon); 
      scmd.CommandType = System.Data.CommandType.StoredProcedure; 
      scmd.Parameters.AddWithValue("@userid",uid); 
      scmd.Parameters.AddWithValue("@password", psw); 

      SqlParameter outparameter = new SqlParameter(); 
      outparameter.ParameterName = "@count"; 
      outparameter.SqlDbType = System.Data.SqlDbType.Int; 
      outparameter.Direction = System.Data.ParameterDirection.Output; 
      scmd.Parameters.Add(outparameter); 

      scon.Open(); 
      scmd.ExecuteScalar(); 

      string count = outparameter.Value.ToString(); 
      if (count == "1") 
      { 
       SqlCommand scmd1= new SqlCommand("spLoginData", scon); 
       scmd1.CommandType = System.Data.CommandType.StoredProcedure; 
       scmd1.Parameters.AddWithValue("@userid", uid); 

       /*SqlParameter outUserType = new SqlParameter(); 
       outUserType.ParameterName = "@usertype"; 
       outUserType.SqlDbType = System.Data.SqlDbType.NText; 
       outUserType.Direction = System.Data.ParameterDirection.Output; 
       scmd1.Parameters.Add(outUserType); 
       */ 
       SqlParameter outUserType = new SqlParameter("@usertype", SqlDbType.NVarChar, 100) { Direction = ParameterDirection.Output }; 
       scmd1.Parameters.Add(outUserType); 

       SqlParameter outLastLogin = new SqlParameter("@lastlogin", SqlDbType.NVarChar, 100) { Direction = ParameterDirection.Output }; 
       scmd1.Parameters.Add(outLastLogin); 

       scmd1.ExecuteNonQuery(); 
       scon.Close(); 

       string usertype,lastlogin; 
       usertype = outUserType.Value.ToString(); 
       lastlogin = outLastLogin.Value.ToString(); 
       } 

      } 
     } 
+1

答えがすべてコードではないように、あなたの答えを再フォーマットしてみてください。ありがとう。 – A5C1D2H2I1M1N2O1R2T1

1

>は、複数の出力パラメータのために、このその作業罰金をお試しください:

using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["conStringEndicia"].ConnectionString)){ 

       using (var sqlCmd = new SqlCommand("endicia.credentialLookup", sqlConnection)) 
       { 

        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure; 
        sqlCmd.Parameters.AddWithValue("@accountNumber", accountNumber); 
        SqlParameter outLogin = new SqlParameter("@login", SqlDbType.NVarChar, 100) { Direction = ParameterDirection.Output }; 
        sqlCmd.Parameters.Add(outLogin); 
        SqlParameter outPassword = new SqlParameter("@password", SqlDbType.NVarChar, 100) { Direction = ParameterDirection.Output }; 
        sqlCmd.Parameters.Add(outPassword); 
        sqlConnection.Open(); 
        sqlCmd.ExecuteNonQuery(); 
        string login, password; 
        login = outLogin.Value.ToString(); 
        password = outPassword.Value.ToString();       
       } 
      } 
関連する問題