簡體   English   中英

使用ExecuteScalar()執行SP時如何在c#中獲取輸出參數的值

[英]How to get values of output parameters in c# while executing SP using ExecuteScalar()

我正在嘗試在C#中執行存儲過程。

存儲過程執行插入操作,並返回列之一的值作為輸出參數。

我需要從c#中執行它並獲取輸出參數的值。

以下是到目前為止我嘗試過的。

SqlParameter[] associateParams = new SqlParameter[10];
            {
                 associateParams[0]=new SqlParameter("@orgName", newAssociate.OrgName);
                 associateParams[1]=new SqlParameter("@createdBy", newAssociate.Email);
                 associateParams[2]=new SqlParameter("@userName", newAssociate.UserName);
                 associateParams[3]=new SqlParameter("@workEmail", newAssociate.Email);
                 associateParams[4]=new SqlParameter("@password", newAssociate.Password);
                 associateParams[5]=new SqlParameter("@teamStrength", "0");
                 associateParams[6]=new SqlParameter("@projName", newAssociate.ProjName);
                 associateParams[7]=new SqlParameter("@userType", "Associate");
                 associateParams[8] = new SqlParameter("@userSalt", SqlDbType.VarChar, 400);
                 associateParams[8].Direction = ParameterDirection.Output;
                 associateParams[9] = new SqlParameter("@activationKey", SqlDbType.Int);
                 associateParams[9].Direction = ParameterDirection.Output;

            }

        using (SqlCommand cmd = con.CreateCommand())
        {
            log.Debug("In command is called");
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = ProcedureName;
            cmd.Parameters.AddRange(param);

            log.Debug("Command is called");
            try
            {
                if (con.State != ConnectionState.Open)
                {
                    con.Open();

                    log.Debug("Con is open");
                }
                cmd.ExecuteScalar();
                log.Debug(cmd.Parameters["@userSalt"].Value.ToString());
                log.Debug(cmd.Parameters["@activationKey"].Value.ToString());

執行上面的操作,成功執行插入,但是對於輸出參數值返回null。

誰能建議我在這里所缺少的。

謝謝

定義輸出參數時,請嘗試以下操作:

         associateParams[8] = new SqlParameter("@userSalt", SqlDbType.VarChar, 400);
         associateParams[8].Value = "";
         associateParams[8].Direction = ParameterDirection.Output;
         associateParams[9] = new SqlParameter("@activationKey", SqlDbType.Int);                 
         associateParams[9].Value = 0;
         associateParams[9].Direction = ParameterDirection.Output;

讓我知道這是否有幫助。

更新:這是我自己的方法

 cmd.Parameters.Add(new SqlParameter("@userSalt", SqlDbType.VarChar, 400));
 cmd.Parameters["@userSalt"].Value = "";
 cmd.Parameters["@userSalt"].Direction = ParameterDirection.Output;

UPDATE1:因為您不使用ExecuteNonQuery。 cmd.ExecuteScalar()更改為cmd.ExecuteNonQuery()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM