2012-07-26 20 views
0

我創建了兩個存儲過程一個用於讀取數據行和一個用於刪除,但我想知道是否可以在讀取它們時刪除記錄,以及它的最佳實踐?我們可以在用SqlReader讀取數據表的同時刪除一行嗎?

例如

while (rdr.Read()) 
{ 
    If(rdr[abc].ToString() != Null) 
    {Maybe delete it ?} 
} 

我的問題是,我可以刪除一行,而閱讀呢? :)

+0

不要for循環的數據表中設定的條件獲得數據行,並刪除它 – 2012-07-26 09:30:33

+0

我編輯我的問題 – 2012-07-26 09:42:06

回答

1

這是你可以用C#做​​什麼

DataTable table = GetTable(); // Get the data table. 
    foreach (DataRow row in table.Rows) // Loop over the rows. 
    { 

     string getvalue= row[1].ToString(); 
     If(getvalue == your condition || getvalue == DBNull.Value) 
      { 
       table.Row.Remove(row[1]); 
      } 
} } 

你有沒有試過這種

SqlCommand cmd = new SqlCommand("select * from yourtable", con); 
     con.Open(); 
     SqlDataReader dr = cmd.ExecuteReader(); 
     while (dr.Read()) 
     { 
      string value=dr[0].ToString(); 
      if (value == "yourcondition") 
      {    
       SqlCommand cmd2 = new SqlCommand("delete from yourtable where columnname ='"+value+"'", con2); 
       con2.Open(); 
       cmd2.ExecuteNonQuery(); 
       con2.Close(); 
      } 
     } dr.Close(); 
     con.Close(); 
相關問題