2012-10-14 16 views
5

Sto utilizzando i parametri di output per ottenere valori dal mio database.Come restituire più parametri di output dalla stored procedure per la funzione C#

Questa è la mia stored procedure:

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 

io non sono sicuro circa i rendimenti alla fine:

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

Dall'altro lato, ecco il codice 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; 
       } 
      } 
     } 
} 

Quando ho eseguito questo codice, ottengo l'errore:

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()

Non so quale sia il modo corretto per inviare molti parametri di output dalla stored procedure, qualcuno può aiutare per favore?

+1

non si usa 'return' per i parametri di output è sufficiente assegnare un valore al loro interno la procedura. Se c'è più di una riga corrispondente in 'ProductList WHERE Reference = @ Reference' (ad esempio' @ ProductCount' è '> 1'), non è deterministico quali righe verranno utilizzate quando si assegna a' @SubscriptionPIN, @ SignupDate'. Anche dal messaggio di errore che stai ricevendo sembra che devi usare ['SqlParameter (String, SqlDbType, Int32)'] (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter .aspx) –

+0

Grazie Martin, non ho notato la tua risposta all'inizio, ma è molto utile. – Yasser

risposta

1

è necessario specificare la lunghezza massima per i parametri 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); 

Rimuovere le dichiarazioni return dalla stored procedure. Non è necessario fare nulla per la restituzione dei parametri di output. (Inoltre, è possibile utilizzare un solo return dichiarazione, e si può restituire solo valori interi. Si potrebbe utilizzare un parametro con la direzione ReturnValue per ottenere quel valore restituito.)

+0

Grazie per aver risolto il mio problema, – Yasser

2

L'esecuzione della procedura termina dopo il primo RITORNO che "Esce incondizionatamente da una query o da una procedura".

considerare tornando entrambi i valori come uno recordset con

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

alla fine della procedura.

+0

Grazie per la tua risposta, lo cambio ma continuo ad avere errori quando eseguo, ci sono cambiamenti nel codice C# da fare? – Yasser

0

Ecco quello che ho provato e si sta lavorando bene

**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

Puoi provare a riformattare la tua risposta in modo che non venga visualizzata come codice? Grazie. – A5C1D2H2I1M1N2O1R2T1

1

> Prova questa il suo bel lavoro per il parametro di uscita multiple:

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();       
       } 
      } 
Problemi correlati