1

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?

Hassan
  • 5,360
  • 2
  • 22
  • 35
sindhu jampani
  • 504
  • 3
  • 10
  • 30
  • Your `ExecuteQuery` method is executing the query so it's up to that method to provide the value. That's your own method so it's up to you how you implement it. – jmcilhinney May 05 '14 at 07:43
  • Why aren't you using the inbuilt `ExecuteQuery` method? What is your implementation of the method like? – shree.pat18 May 05 '14 at 07:45
  • 1
    Don't use inline query, create a store procedure for this and return the accountID from that SP as output parameter. – Rohit Vyas May 05 '14 at 07:47

4 Answers4

3

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.

Hassan
  • 5,360
  • 2
  • 22
  • 35
0

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.

Anthony Horne
  • 2,522
  • 2
  • 29
  • 51
0

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)

LakshmiNarayanan
  • 1,158
  • 9
  • 12
0
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);
Praveen
  • 55,303
  • 33
  • 133
  • 164
Anoop
  • 1