Question

I have a method like this

private string AccountCreation()
{
     string accountId="";

     using (SqlConnection connection = new SqlConnection(ConnectionString))
     {
         connection.Open();
         SqlCommand command = new SqlCommand();
         command.Connection = connection;
         StringBuilder sql = new StringBuilder();
         sql.AppendLine("SELECT ACCOUNT_ID,CUSTOMER_ID FROM T_ACCOUNT order by ACCOUNT_ID desc");
         sql.AppendLine("SET IDENTITY_INSERT T_ACCOUNT ON");
         sql.AppendLine("INSERT INTO  T_ACCOUNT (ACCOUNT_ID,CUSTOMER_ID)");
         sql.AppendLine("SELECT ACCOUNT_ID + 1, CUSTOMER_ID +1 FROM T_ACCOUNT Where ACCOUNT_ID = (select max(ACCOUNT_ID) from T_ACCOUNT)");
         sql.AppendLine("SET IDENTITY_INSERT T_ACCOUNT OFF");
         accountId = Convert.ToString(sql.AppendLine("SELECT top 1 ACCOUNT_ID FROM T_ACCOUNT order by ACCOUNT_ID desc"));
         string strUpdateQuery = sql.ToString();
         ExecuteQuery(strUpdateQuery, command);                
     }
     return accountId;
}

Now accountId is holding the query but not the value returned after execution of the query. I want the value in that string. Can anyone help me?

Was it helpful?

Solution

For getting value from the query. you need ExecuteScalar method.

object oRetVal = command.ExecuteScalar();
string accountId = string.Empty;

if(oRetVal != null) 
{
    accountId = oRetVal.ToString();
}

However, it is recommend to use store procedure.

OTHER TIPS

I assume you are looking for the "TOP 1 Account_ID" from the query. What you have done there will not work (or give you what you want). You will need to either send in a output parameter to put the accountID in, or run fetch the data using datareader or dataset.

You'll have to bind the output of your ExecuteQuery to an object. check if this returns any result and populates the accID.

var accID = ExecuteQuery(strUpdateQuery, command)

public string ExecuteQuery(string query,SqlCommand cmd)
{
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = query;
    object i=cmd.ExecuteScalar();
    return i.ToString();
}

After this just assign this to the accounted

accountId = ExecuteQuery(strUpdateQuery, command);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top