2013-03-04 122 views
0

我是c#中的一名真正的新手。從table1中選擇數據並將其複製到table2中

我在這裏看到過很多像這樣的問題。但是,在嘗試時,我無法獲得我的代碼。

我想檢索某一行的所有列,然後將其傳送到同一個數據庫的另一個表。

所以基本上,從table1檢索數據,並將其複製到table2各自的列。

我已經嘗試了這麼多的代碼。 而我很困惑如何直接調用檢查字符串,而不是在「」中定義str1字符串中的每一列。

string check = "select * from custdetails where billid = @billid "; 

     SqlCommand cmd1 = new SqlCommand(check , conn); 
     cmd1.Parameters.AddWithValue("@billid", billid); 

     DataSet ds = new DataSet(); 
     SqlDataAdapter da = new SqlDataAdapter(cmd1); 
     da.Fill(ds); 
     // string str1; 
     int count = ds.Tables[0].Rows.Count; 
     if (count > 0) 
     { 
      string str1 = ds.Tables[0].Rows[0][""].ToString(); 
     } 

我真的沒有太多關於c#的想法。 感謝您的幫助。

+0

您是否需要修改或使用該數據作爲應用程序中的其他任何內容?如果不是,你爲什麼不用一個命令來做到這一點。 – 2013-03-04 10:08:56

+0

您是否試圖構建一個'INSERT'語句來將數據放入'table2'中? – 2013-03-04 10:10:31

回答

3

您可以通過這樣做:

INSERT INTO table2 (SELECT * FROM table1 WHERE billid = @billid) 

上面是GUD只有當table1 & table2有相同的結構。如果兩個表中有你需要改變SELECT *SELECT [COLUMNS ,]...

一個你完成複製數據,那麼你可以讀取數據進行到您的應用程序

string check = "select * from custdetails where billid = @billid "; 

SqlCommand cmd1 = new SqlCommand(); 
// use the command object to copy table first.... 
cmd1.Connection = conn; 
cmd1.CommandText = "INSERT INTO table2 (SELECT * FROM table1 WHERE billid = @billid)"; 
cmd1.ExecuteNonQuery(); 

//then continue doing the normal work 
cmd1.CommandText = check; 
cmd1.Parameters.AddWithValue("@billid", billid); 

DataSet ds = new DataSet(); 
SqlDataAdapter da = new SqlDataAdapter(cmd1); 
da.Fill(ds); 
// string str1; 
int count = ds.Tables[0].Rows.Count; 
if (count > 0) 
{ 
    string str1 = ds.Tables[0].Rows[0][""].ToString(); 
} 
+0

這真的有幫助...但我接近關鍵字選擇錯誤的語法錯誤。必須聲明標量變量「@billid」 – 2013-03-04 10:26:05

1

您可以通過實現它不同的結構下面一行。

INSERT INTO targettable 
SELECT * FROM custdetails WHERE billid = @billid; 
相關問題