2012-03-13 7 views
0

다음 코드를 가지고 있고 count를하려고 할 때 else() == 0을 삽입하면 다른 것보다 update.I가 잘못되었다는 것을 알 수 없습니다. 쿼리가 완료되었지만 페이지가 다시로드되고 데이터가 삽입되거나 업데이트되지 않으면 다음 페이지로 이동합니다.이 작업은 버튼을 누를 때 수행되어야합니다.이 작업에 도움이 될 수 있습니까? 나는 전에 물어하지만의 대답은 내 자신에 의해 지금 시도하지하지만 나는 내가 저장으로 되돌아갑니다 상황이 종류에 잡힐 때count then then insert else update

string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
      if (string.IsNullOrEmpty(ip)) 
      { 
       ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; 
      } 


      String id_sesiune; 
      id_sesiune = Session.SessionID; 

      SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString); 
      con.Open(); 
      SqlCommand cmd1 = new SqlCommand("SELECT count(*) from Raspunsuri where id_intrebare=2",con); 

      int read = Convert.ToInt16(cmd1.ExecuteScalar()); 


      if (read == 0) 
      { 
       SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values(@raspuns,@cnp,@data,'2',@ip,@idsesiune)", con); 
       cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]); 
       cmd.Parameters.AddWithValue("@raspuns", textbox2.Text); 
       cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime()); 
       cmd.Parameters.AddWithValue("@ip", ip); 
       cmd.Parameters.AddWithValue("@idsesiune", id_sesiune); 

       try 
       { 
        con.Open(); 
        cmd.ExecuteNonQuery(); 
        Response.Redirect("User3.aspx"); 
       } 

       catch (Exception ex) 
       { 
        Console.WriteLine("Error:" + ex); 
       } 
       finally 
       { 
        con.Close(); 
       } 


      } 

      else 
      { 

       SqlCommand cmd = new SqlCommand("UPDATE Raspunsuri SET [email protected],[email protected],[email protected],id_intrebare=2,[email protected],[email protected] WHERE id_intrebare=2", con); 
       cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]); 
       cmd.Parameters.AddWithValue("@raspuns", textbox2.Text); 
       cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime()); 
       cmd.Parameters.AddWithValue("@ip", ip); 
       cmd.Parameters.AddWithValue("@idsesiune", id_sesiune); 

       try 
       { 
        con.Open(); 
        cmd.ExecuteNonQuery(); 
        Response.Redirect("User3.aspx"); 
       } 

       catch (Exception ex) 
       { 
        Console.WriteLine("Error:" + ex); 
       } 
       finally 
       { 
        con.Close(); 
       } 

      } 
+0

예외가 있습니까? 'Raspunsuri에서 SELECT count (*) id_intrebare = 2'가 어떤 행을 반환합니까? – sll

+0

반환하지 않는 경우 업데이트를 삽입하고 싶습니다. – Rares

+0

행이 반환되지 않으면 단계로 이동하여 업데이트 섹션으로 이동하십시오. 오류는 발생하지 않지만 오류 및 데이터는 삽입되지 않습니다. – Turbot

답변

3

을 반복하기위한 problem.Sorry 무엇인지 볼 수없는 것 순서.

CREATE PROCEDURE UpsertRasPunsuri(@keyID int, @cnp int, @raspuns nvarchar(30), 
        @data smalldatetime, @ip nvarchar(30), @idsesiune int) 
    AS 
    BEGIN 
     declare @cnt int 
     SELECT @cnt = count(*) from Raspunsuri where [email protected] 
     if @cnt = 0 
      INSERT INTO Raspunsuri Values(@raspuns,@cnp,@data,2,@ip,@idsesiune) 
     else 
      UPDATE Raspunsuri SET 
        [email protected],[email protected],[email protected], 
        id_intrebare=2,[email protected],[email protected] 
      WHERE [email protected]  
    END 

이제 코드는 내가 열 유형과 길이에, 당신의 테이블에 여기에 가정을 많이 만들어 물론이 방법

try 
{ 
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString); 
    con.Open(); 
    SqlCommand cmd = new SqlCommand("UpsertRasPunsuri",con); 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.Parameters.AddWithValue("@keyID", 2); 
    cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]); 
    cmd.Parameters.AddWithValue("@raspuns", textbox2.Text); 
    cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime()); 
    cmd.Parameters.AddWithValue("@ip", ip); 
    cmd.Parameters.AddWithValue("@idsesiune", id_sesiune); 
    con.Open(); 
    cmd.ExecuteNonQuery(); 
    Response.Redirect("User3.aspx"); 
} 

catch (Exception ex) 
{ 
    Console.WriteLine("Error:" + ex); 
} 
finally 
{ 
    con.Close(); 
} 

에서 단순화합니다.
그러나 이것은 비교적 쉽게 적응할 수 있습니다. 이제 VS 또는 SSMS에서 저장 프로 시저를 실행하면 데이터 액세스 코드의 오류를 배제 할 수 있습니다.

+0

절차없이? – Rares