2013-05-16 68 views
1

我有2個表,即配置文件和信息。更新多個表

我的表是這樣的:

PROFILE

| p_Id | FirstName | LastName | 

| 1 | Jack  | Cole  | 
| 2 | Cynthia | Cole  | 
| 3 | Robert | Cole  | 

信息

| I_Id | childsID | fathersID | mothersID | Country | 

| 1 | 1  | 3   | 2   | USA  | 

我在文本框中顯示它們檢索從這些表中的值,我選擇的查詢是:

SELECT p.p_Id, p.FirstName, p.LastName, i.*, 
(SELECT pp.FirstName+' '+pp.LastName FROM Profile pp WHERE pp.p_Id=i.childsID) AS child, 
(SELECT pp.FirstName+' '+pp.LastName FROM Profile pp WHERE pp.p_Id=i.fathersID) AS father, 
(SELECT pp.FirstName+' '+pp.LastName FROM Profile pp WHERE pp.p_Id=i.mothersID) AS mother 
    FROM Info i 
     INNER JOIN Profile p 
      ON p.p_Id=i.childsID 

與選擇沒有問題,我能夠在文本框顯示的值,但問題是,我不能更新它們,到目前爲止我這個嘗試:

using (SqlCommand cmd = con.CreateCommand()) 
    { 
     con.Open(); 
     cmd.CommandText = @"UPDATE Profile SET [email protected], [email protected] WHERE p_Id = @pid; 
          UPDATE Info SET [email protected], [email protected], [email protected], [email protected] WHERE I_Id = @iid;"; 

     cmd.Parameters.Add(new SqlParameter("@fname", txtfname.Text)); 
     cmd.Parameters.Add(new SqlParameter("@lname", txtlname.Text)); 
     cmd.Parameters.Add(new SqlParameter("@child", txtchild.Text)); 
     cmd.Parameters.Add(new SqlParameter("@father", txtfather.Text)); 
     cmd.Parameters.Add(new SqlParameter("@mother", txtmother.Text)); 
     cmd.Parameters.Add(new SqlParameter("@country", txtcountry.Text)); 
     cmd.Parameters.Add(new SqlParameter("@pid", txtpid.Text)); 
     cmd.Parameters.Add(new SqlParameter("@iid", txtiid.Text)); 
     cmd.ExecuteNonQuery(); 
     Response.Write("alert('DATA UPDATED')"); 
    } 

我使用C#和Asp。淨 感謝提前:)天佑

+0

我不知道,如果它是通過一個好主意將一批SQL更新語句放入單個'SqlCommand'對象的'CommandText'中,並添加批次中所有更新將使用的參數。 –

+1

此問題正在重複發佈,另請參閱http://stackoverflow.com/questions/16586456/update-query-with-multiple-tables和http://stackoverflow.com/questions/16588835/select-to-update – criticalfix

回答

0

檢查MSDN:SqlParameter Constructor (String, Object)

當您指定的值參數的對象時,SqlDbType是從微軟的.NET Framework類型對象的推斷。

所以,當你路過的int類型的參數,你需要將文本轉換價值爲整數:

cmd.Parameters.Add(new SqlParameter("@pid", int.Parse(txtpid.Text))); 

或更好:

int tempIntValue; 
cmd.Parameters.Add(new SqlParameter("@pid", int.TryParse(txtpid.Text, out tempIntValue)? 
    (object)intTempValue: (object)DbNull.Value));