2016-05-30 10 views
0

Я работаю над проектом, чтобы десерилизовать XML и прочитать его в базе данных.Должен объявить скалярную переменную

У меня есть следующий код:

query += ", NationalRegistrationDate = @NationalRegistrationDate"; 
     command1 = new SqlCommand(query, connection); 
     DateTime myDate = DateTime.ParseExact(d, "yyyyMMdd", 
     System.Globalization.CultureInfo.InvariantCulture); 
     command1.Parameters.AddWithValue("@NationalRegistrationDate", myDate); 

Я получаю эту ошибку:

must declare the scalar variable @NationalRegistrationDate

Кто-нибудь знает, почему я получаю эту ошибку?

Вот остальная часть кода:

 using (var connection = new SqlConnection(connetionString)) 
     { 
      try 
      { 
       connection.Open(); 
      } 
      catch(Exception e)  
      { 
       Console.WriteLine(e.Message); 
      } 
      Console.WriteLine("DatabasConnection Done"); 
      DateTime datum = DateTime.Now; 
      string LastChangedBy = "System"; 

      foreach (Person p in myPersons) 
      { 
       SqlCommand command1 = new SqlCommand(); 
       try 
       { 
        command1 = Avreg(p.UnregistrationReason, p.GivenNameNumber, p.ProtectedIdentity, p.CitizenshipDate, p.NationalRegistrationDate, connection); 

       command1.Parameters.AddWithValue("@PersonalIdentityNumber", string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber)); 
       command1.Parameters.AddWithValue("@FirstName", p.FirstName ?? (object)DBNull.Value); 
       command1.Parameters.AddWithValue("@LastName", p.LastName ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@NationalRegistrationCountyCode", p.NationalRegistrationCountyCode ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@NationalRegistrationMunicipalityCode", p.NationalRegistrationMunicipalityCode ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@NationalRegistrationDistributionAddress1", p.NationalRegistrationDistributionAddress1 ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@NationalRegistrationDistributionAddress2", p.NationalRegistrationDistributionAddress2 ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@NationalRegistrationPostCode", p.NationalRegistrationPostCode ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@NationalRegistrationCity", p.NationalRegistrationCity ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@BirthCountyCode", p.BirthCountyCode ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@UnregistrationDate", p.UnregistrationDate ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@BirthParish", p.BirthParish ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@CitizenshipCode", p.CitizenshipCode ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@CitizenshipDate", p.CitizenshipDate ?? DBNull.Value.ToString()); 
       //command1.Parameters.AddWithValue("@NationalRegistrationDate", p.NationalRegistrationDate ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@ForeignDistrubtionAddress1", p.ForeignDistrubtionAddress1 ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@ForeignDistrubtionAddress2", p.ForeignDistrubtionAddress2 ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@ForeignDistrubtionAddress3", p.ForeignDistrubtionAddress3 ?? DBNull.Value.ToString()); 
       command1.Parameters.AddWithValue("@ForeignBirthCity", p.ForeignBirthCity ?? DBNull.Value.ToString()); 

       command1.Parameters.AddWithValue("@LastChangedBy", LastChangedBy); 
       command1.Parameters.AddWithValue("@LastChangedDate", datum); 

       command1.ExecuteNonQuery(); 

       Console.WriteLine(string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber)); 



       } 
       catch (Exception e) 
       { 
        Console.WriteLine(e.Message); 
       } 

      } 
     } 

     Console.WriteLine("Done"); 
     Console.WriteLine("Alla fält uppdaterade"); 

    Console.ReadKey(); 

     }// Put a break-point here, then mouse-over PersonalIdentityNumber... deserializedList contains everything if you need it 
     catch (Exception e) 
     { 

      Console.Write(" ---- FEL VID INLÄSNINGEN ------ " + e.Message); 
      Console.ReadKey(); 
     } 

    } 






    public static SqlCommand Avreg(string s, string t, string p, string c, string d, SqlConnection connection) 
    { 
     try 
     { 


     var query = "UPDATE Seamen SET FirstName = @FirstName, "+ 
      "LastName = @LastName, " + 
      "NationalRegistrationCountyCode = @NationalRegistrationCountyCode, " + 
      "NationalRegistrationMunicipalityCode = @NationalRegistrationMunicipalityCode, " + 
      "NationalRegistrationDistributionAddress1 = @NationalRegistrationDistributionAddress1, " + 
      "NationalRegistrationDistributionAddress2 = @NationalRegistrationDistributionAddress2, " + 
      "UnregistrationDate = @UnregistrationDate, " + 
      "NationalRegistrationPostCode = @NationalRegistrationPostCode, " + 
      "NationalRegistrationCity = @NationalRegistrationCity, " + 
      "BirthCountyCode = @BirthCountyCode, " + 
      "BirthParish = @BirthParish, " + 
      "CitizenshipCode = @CitizenshipCode, " + 
      "ForeignDistrubtionAddress1 = @ForeignDistrubtionAddress1, " + 
      "ForeignDistrubtionAddress2 = @ForeignDistrubtionAddress2, " + 
      "ForeignDistrubtionAddress3 = @ForeignDistrubtionAddress3, " + 
      "ForeignBirthCity = @ForeignBirthCity, " + 
      "LastChangedBy = @LastChangedBy, " + 
      "LastChangedDate = @LastChangedDate"; 

     SqlCommand command1; 



     if (c == "0") 
     { 
      query += ", CitizenshipDate = null"; 
      command1 = new SqlCommand(query, connection); 




     } 
     else 
     { 
      query += ", CitizenshipDate = @CitizenshipDate"; 
      command1 = new SqlCommand(query, connection); 

      command1.Parameters.AddWithValue("@CitizenshipDate", c ?? DBNull.Value.ToString()); 

     } 

     if (d == "0") 
     { 
      query += ", NationalRegistrationDate = null;"; 
      command1 = new SqlCommand(query, connection); 

     } 
     else 
     { 
      query += ", NationalRegistrationDate = @NationalRegistrationDate"; 
      command1 = new SqlCommand(query, connection); 
      DateTime myDate = DateTime.ParseExact(d, "yyyyMMdd", 
      System.Globalization.CultureInfo.InvariantCulture); 
      command1.Parameters.AddWithValue("@NationalRegistrationDate", myDate); 

     } 


     if (p == "J") 
     { 

      query = "UPDATE Seamen SET FirstName ='Skyddad personuppgift', " + 
      "LastName = 'Se hjälptext', " + 
      "ProtectedIdentity = '1', " + 
      "NationalRegistrationCountyCode = NULL, " + 
      "NationalRegistrationMunicipalityCode = NULL, " + 
      "NationalRegistrationCoAddress = NULL, " + 
       "NationalRegistrationDistributionAddress1 = NULL, " + 
       "NationalRegistrationDistributionAddress2 = NULL, " + 
      "UnregistrationDate = NULL, " + 
      "NationalRegistrationPostCode = NULL, " + 
      "NationalRegistrationCity = NULL, " + 
      "BirthCountyCode = NULL, " + 
      "BirthParish = NULL, " + 
      "CitizenshipCode = NULL, " + 
      //"CitizenshipDate = @CitizenshipDate, " + 
      "NationalRegistrationDate = NULL, " + 
      "ForeignDistrubtionAddress1 = NULL, " + 
      "ForeignDistrubtionAddress2 = NULL, " + 
      "ForeignDistrubtionAddress3 = NULL, " + 
      "UnregistrationReason = NULL, " + 
      "ForeignBirthCity = NULL, " + 
      "LastChangedBy = @LastChangedBy, " + 
      "GivenNameNumber = NULL, " + 
      "LastChangedDate = @LastChangedDate WHERE PersonalIdentityNumber = @PersonalIdentityNumber"; 



      command1 = new SqlCommand(query, connection); 
      command1.Parameters.Clear(); 
      return command1; 
     } 

     if ((!string.IsNullOrEmpty(s)) && !string.IsNullOrEmpty(t)) 
     { 
      query += ", UnregistrationReason = @UnregistrationReason"; 
      query += ", GivenNameNumber = @GivenNameNumber "; 

      command1 = new SqlCommand(query, connection); 

      command1.Parameters.AddWithValue("@UnregistrationReason", s ?? DBNull.Value.ToString()); 
      command1.Parameters.AddWithValue("@GivenNameNumber", t ?? DBNull.Value.ToString()); 

     } 
     else if (!string.IsNullOrEmpty(s) && string.IsNullOrEmpty(t)) 
     { 
      query += ", UnregistrationReason = @UnregistrationReason, GivenNameNumber = @GivenNameNumber WHERE PersonalIdentityNumber = @PersonalIdentityNumber"; 
      command1 = new SqlCommand(query, connection); 

      t = "00"; 
      command1.Parameters.AddWithValue("@UnregistrationReason", s ?? DBNull.Value.ToString()); 
      command1.Parameters.AddWithValue("@GivenNameNumber", t ?? DBNull.Value.ToString()); 

     } 

     else if (string.IsNullOrEmpty(s) && !string.IsNullOrEmpty(t)) 
     { 
      query += ", GivenNameNumber = @GivenNameNumber WHERE PersonalIdentityNumber = @PersonalIdentityNumber"; 
      command1 = new SqlCommand(query, connection); 

      command1.Parameters.AddWithValue("@GivenNameNumber", t ?? DBNull.Value.ToString()); 

     } 
     else 
     { 

       query += ", GivenNameNumber = @GivenNameNumber WHERE PersonalIdentityNumber = @PersonalIdentityNumber"; 
       t = "00"; 
       command1 = new SqlCommand(query, connection); 

       command1.Parameters.AddWithValue("@GivenNameNumber", t ?? DBNull.Value.ToString()); 

       return command1; 

     } 
     return command1; 

    } 


    catch(Exception e) 
{ 
    throw; 
} 

    } 
+3

Там это слишком много кода. Можете ли вы сузить его, пожалуйста? –

+0

@PatrickHofman Done –

+0

Почему вы комментируете '//command1.Parameters.AddWithValue (« @ NationalRegistrationDate »'? –

ответ

2

Логика внутри метода AvReg испорчено. Первый if создает SqlCommand, а второй воссоздает sqlcommand, удаляя параметры, добавленные в первый, если (хотя это должно дать ошибку в параметре @CitizenshipDate.)

В любом случае, создайте команду перед входом в ifs и установите текст команды перед выходом из метода

public static SqlCommand Avreg(string s, string t, string p, string c, string d, SqlConnection connection) 
{ 
    try 
    { 
     var query = "UPDATE ...." 
     SqlCommand command1 = new SqlCommand(); 



     if (c == "0") 
     { 
      query += ", CitizenshipDate = null"; 
     } 
     else 
     { 
      query += ", CitizenshipDate = @CitizenshipDate"; 
      command1.Parameters.AddWithValue("@CitizenshipDate", string.IsNullOrEmpty(c) ? DBNull.Value : (object)c); 
     } 

     if (d == "0") 
     { 
      query += ", NationalRegistrationDate = null;"; 
     } 
     else 
     { 
      query += ", NationalRegistrationDate = @NationalRegistrationDate"; 
      DateTime myDate = DateTime.ParseExact(d, "yyyyMMdd", 
      System.Globalization.CultureInfo.InvariantCulture); 
      command1.Parameters.AddWithValue("@NationalRegistrationDate", myDate); 
     } 
     command1.CommandText = query; 
     command1.Connection = connection; 
    } 
    return command1; 
} 

сказал, что есть другие ошибки, как указано в комментарии на ваш вопрос, (как в DbNull.Value.ToString(), как г-н Gravell сказал вам), и я хотел бы посмотреть на переместите все создания параметров вне цикла for, в то время как внутри цикла я бы изменил только значения.

SqlCommand command1 = new SqlCommand(); 
command1.Parameters.Add("@PersonalIdentityNumber", SqlDbType.NVarChar); 
... add other parameters with the exact datatype here 
foreach (Person p in myPersons) 
{ 
    SqlCommand command1 = new SqlCommand(); 
    try 
    { 
     // Pass the command created above, not recreate another one... 
     Avreg(command1, p.UnregistrationReason, 
         p.GivenNameNumber, p.ProtectedIdentity, 
         p.CitizenshipDate, p.NationalRegistrationDate); 

     command1.Parameters["@PersonalIdentityNumber"].Value = string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber)); 
     .... set the values for the other parameters ..... 
     command1.ExecuteNonQuery(); 
    } 
    catch(.....) 
    ... 
} 

Теперь Avreg не должно создавать SqlCommand и вернуть его, Mothod просто использует команду, переданную в качестве аргумента и добавить необходимые параметры, только если они не являются настройками уже присутствуют в SqlCommand

public static void Avreg(SqlCommand command1, string s, string t, 
       string p, string c, string d) 
{ 

    var query = "UPDATE...."; 

    if (c == "0") 
    { 
     query += ", CitizenshipDate = null"; 
    } 
    else 
    { 
     query += ", CitizenshipDate = @CitizenshipDate"; 
     if(!command1.Parameters.Contains("@CitizenshipDate")) 
      command1.Parameters.Add("@CitizenshipDate", SqlDbType.NVarChar); 
     command1.Parameters["@CitizenshipDate"].Value = string.IsNullOrEmpty(c) ? DBNull.Value : (object)c); 
    } 
    ..... 
} 
+0

Я знаю, что вы имеете в виду, но факт в том, что я сделал это нарочно.Если одно поле в таблице является конкретным значением ('if (p ==" J ")'), то все остальные поля должны быть пустыми, поэтому он воссоздает sqlcommand, если это условие истинно. –

+0

Дело в том, что не воссоздайте SqlCommand, измените текст запроса так, как считаете нужным. Также Parameters представляет собой SqlParameterCollection со всем методом, который должен присутствовать в коллекции. Таким образом, вы можете проверить наличие отдельного параметра, удалить его или очистить все. – Steve

+1

Спасибо тебе, Стив! Это сработало –