2011-12-27 1 views
1

내 asp.net 응용 프로그램에서 데이터베이스를 업데이트하려고합니다. 업데이트 된 필드는 텍스트 상자에 설정됩니다.업데이트 테이블 SQL 서버 필드가 비어있을 수도 있음

SqlCommand cmd = new SqlCommand(); 
cmd.Connection = con; 

cmd.ExecuteNonQuery(); 
cmd.CommandText = "update dbo.User_Info SET [email protected], [email protected],[email protected],[email protected],[email protected],[email protected] where UserName [email protected]"; 
cmd.Parameters.Add("FirstName", SqlDbType.VarChar).Value = TextFirstName.Text; 
cmd.Parameters.Add("LastName", SqlDbType.VarChar).Value = TextLastName.Text; 
cmd.Parameters.Add("Degree", SqlDbType.VarChar).Value = TextDegree.Text; 
cmd.Parameters.Add("Organization", SqlDbType.VarChar).Value = TextOrg.Text; 
cmd.Parameters.Add("Phone", SqlDbType.VarChar).Value = TextPhone.Text; 
cmd.Parameters.Add("Ext", SqlDbType.VarChar).Value = TextExt.Text; 

그러나 일부 필드는 전혀 업데이트하지 않으려합니다. 코드를 수정하려면 어떻게해야할까요?

cmd.CommandText = "update dbo.User_Info SET [email protected] where UserName [email protected]"; 

인가 거기 : 예를 들어 은, 그냥 명령 그러나 다른 사람이 단지 때문에 명령이 될 것 "학위"를 업데이트 할

cmd.CommandText = "update dbo.User_Info SET [email protected] where UserName [email protected]"; 

해야 FIRSTNAME을 업데이트한다고 가정 다양한 시나리오를 고려하기위한 보편적 명령?

답변

2

유니버설? 나는 그것을 의심한다. 일부 옵션 :

동적으로 필드를 추가하여 입력을 기반으로 UPDATE 문을 사용자 정의

string sql = "update dbo.User_Info SET "; 
if (TextFirstName.Text != null) 
{ 
    sql += "[email protected], "; 
    cmd.Parameters.Add("FirstName", SqlDbType.VarChar).Value = TextFirstName.Text; 
} 
// etc. 

는 NULL paramteres를 확인하고이 NULL 경우 초기 값을 떠날 SQL 문을 변경 :

// If @FirstName is NULL, "update" with the original value 
cmd.CommandText = "update dbo.User_Info SET FirstName=COALESCE(@FirstName, FirstName)," 
// etc. 
0

컨트롤의 내용에 따라 업데이트 쿼리를 작성해야합니까? 당신이 그들을 반복이 (원유 예는 다음과) 같이가, 비어 있지 않은 경우에만 사용할 수 있습니다 : 그런

string query = "UPDATE User_Info SET "; 
foreach (Control ctl in panel.Controls) 
{ 
    if (ctl.Type == "Textbox") 
    { 
     query += ctl.Tag + " = " + "@" + ctl.Tag //assuming you preload the table names on the tags of the controls and you wanna name the parameters like that 
     cmd.Parameters.AddWithValue("@" + ctl.Tag, ctl.Text); 
     query += ", " 
    } 
} 
//You need here something to eliminate the last comma 
query += "WHERE UserName [email protected]" 
cmd.Parameters.AddWithValue("@username", _usrName); 

뭔가 일할 수 있습니다. 물론 iterating 대신에 항상 switch 문장을 사용할 수 있습니다.

+1

'Control'에는'Type' 속성이 없습니다. 'typeof (TextBox) .Equals (ctl.GetType()) '을 수행 할 수 있습니다. – Amy

+0

쿼리와 관련이없는 다른 텍스트 상자가 있으면 멋지게 보입니까? 어떻게 구별 할 수 있습니까? –

+0

태그를 설정하지 마십시오. 그것은 빠르며 더럽습니다 (유지하기가 매우 어렵지는 않음). 또한, Inuyasha가 말한 것. – CMPerez