0

有這樣我怎麼行值從SQL Server轉換爲字符串在C#中

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; 
} 

現在accountId的方法是持有查詢,但不執行查詢後返回的值。我想要那個字符串中的值。誰能幫我?

+0

你'ExecuteQuery'方法執行查詢,以便它是由該方法提供的價值。這是你自己的方法,所以你如何實現它取決於你。 – jmcilhinney

+0

爲什麼不使用內置的ExecuteQuery方法?你的方法的實現是什麼樣的? –

+1

請勿使用內嵌查詢,爲此創建一個存儲過程,並將該SP的accountID作爲輸出參數返回。 –

回答

3

對於從查詢中獲得價值。你需要ExecuteScalar方法。

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

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

但是,推薦使用store procedure

+0

它顯示了一個錯誤.ExecuteScalr:commandText屬性尚未初始化 –

0

我假設您正在查詢查詢中的「TOP 1 Account_ID」。你在那裏做了什麼不會工作(或給你你想要的)。您需要發送一個輸出參數來放入accountID,或者使用datareader或dataset運行獲取數據。

0

您必須將ExecuteQuery的輸出綁定到對象。 檢查是否返回任何結果並填充accID。

var accID = ExecuteQuery(strUpdateQuery, command)

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

在此之後只是這個分配給佔

accountId = ExecuteQuery(strUpdateQuery, command); 
相關問題