简体   繁体   English

将datetime插入为字符串C#SQL-server

[英]Inserting datetime as string C# SQL-server

I have a SQL-server and a column called CitizenshipDate . 我有一个SQL服务器和一个名为CitizenshipDate的列。 That column is of type datetime in the SQL. 该列在SQL中的类型为datetime

However, the problem is that it can have the value '0' which is NOT a datetime value but rather a string value. 但是,问题在于它可以具有值'0' ,该值不是日期时间值,而是字符串值。

So what I'm trying to do is to handle it as a string in C# when inserting it values but get the error: 所以我想做的是在插入C#值时将其作为字符串处理,但出现错误:

Conversion failed when converting datetime from character string. 从字符串转换日期时间时转换失败。

I get that error because I'm trying to insert string into a datetime in the SQL-server. 我收到该错误,因为我试图在SQL服务器的日期时间中插入字符串。

Here is my code: 这是我的代码:

 class Person {
       public string PersonalIdentityNumber { get; set; }
       public string SpecialIdentityNumber { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string CitizenshipDate { get; set; }

}



  List<FolkbokforingspostTYPE> deserializedList = new List<FolkbokforingspostTYPE>();
            deserializedList = Deserialize<List<FolkbokforingspostTYPE>>();


            var myPersons = Deserialize<List<FolkbokforingspostTYPE>>()
                .Select(x => new Person
                {
                    PersonalIdentityNumber = x.Personpost.PersonId.PersonNr,
                    SpecialIdentityNumber = x.Personpost.PersonId.Tilltalsnamnsmarkering != null ? x.Personpost.PersonId.Tilltalsnamnsmarkering : null, 
                    LastName = x.Personpost.Namn.Efternamn,
                    FirstName = x.Personpost.Namn.Fornamn,
                    CitizenshipDate = x.Personpost.Medborgarskap != null ? x.Personpost.Medborgarskap.Medborgarskapsdatum : null             

                });



            string connetionString = null;


            SqlDataAdapter adpter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            XmlReader xmlFile;



            connetionString = "Data Source=tsrv2062;Initial Catalog=Bums;User ID=BumsUser;Password=2tusen7Bums";


            xmlFile = XmlReader.Create("navetout.xml", new XmlReaderSettings());
            ds.ReadXml(xmlFile);


            using (var connection = new SqlConnection(connetionString))
            {
                connection.Open();
                DateTime datum = DateTime.Now;
                string LastChangedBy = "System";

                foreach (Person p in myPersons)
                {

                    SqlCommand command1 = Avreg(p.UnregistrationReason, p.GivenNameNumber,p.ProtectedIdentity, p.CitizenshipDate, connection);


                    command1.Parameters.AddWithValue("@PersonalIdentityNumber", string.Format("{0}{1}", p.PersonalIdentityNumber, p.SpecialIdentityNumber));
                    command1.Parameters.AddWithValue("@FirstName", p.FirstName);
                    command1.Parameters.AddWithValue("@LastName", p.LastName);
                    command1.ExecuteNonQuery();

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


                }
            }

            Console.WriteLine("Done");


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

           //     throw;
           // }
            Console.ReadKey();
        }

        public static SqlCommand Avreg(string s, string t, string p, string c, SqlConnection connection)
        {
            var query = "UPDATE Seamen SET FirstName = @FirstName, "+
                "LastName = @LastName, "+

            SqlCommand command1;


//Here is the `CitizenshipDate` 
            if (c == "0")
            {
                query += ", CitizenshipDate = '0'";
                command1 = new SqlCommand(query, connection);
                command1.Parameters.Clear();



            }
            else
            {
                query += ", CitizenshipDate = @CitizenshipDate";
                command1 = new SqlCommand(query, connection);
                command1.Parameters.Clear();
                command1.Parameters.AddWithValue("@CitizenshipDate", c ?? DBNull.Value.ToString());

            }


//Ignore these if statements
             if ((!string.IsNullOrEmpty(s)) && !string.IsNullOrEmpty(t))
            {

            }
            else
            {

                    query += ", GivenNameNumber = @GivenNameNumber WHERE PersonalIdentityNumber = @PersonalIdentityNumber";
                    t = "00";
                    command1 = new SqlCommand(query, connection);
                    command1.Parameters.Clear();
                    command1.Parameters.AddWithValue("@GivenNameNumber", t ?? DBNull.Value.ToString());

                    return command1;

            }
             return command1;
        }

Please note that I cannot change the type in the database. 请注意,我无法更改数据库中的类型。 I somehow need a way to insert the value from String. 我不知何故需要一种从String插入值的方法。 Can someone help ? 有人可以帮忙吗?

If the column does not allow nulls, then you can use NULL to represent "0", and then in code, when loading the record, replace NULL with "0" in the UI. 如果该列不允许为空,则可以使用NULL表示“ 0”,然后在代码中,在加载记录时,在UI中将NULL替换为“ 0”。 Or, if you do allow NULLS and need another value to represent "0", you can use an arbitrary date you wouldn't normally use like '1/1/1753' (the lowest value for SQL datetime) or '1/1/1900' (lowest for smalldatetime) or something like that. 或者,如果您确实允许NULL并需要另一个值来表示“ 0”,则可以使用通常不会使用的任意日期,例如“ 1/1/1753”(SQL datetime的最小值)或“ 1/1” / 1900'(smalldatetime的最低值)或类似的值。 Any date that is these dates represents "0". 这些日期中的任何日期都代表“ 0”。 So the conversion to "0" happens within the app, not stored in the database. 因此,转换为“ 0”是在应用程序中发生的,而不是存储在数据库中。

If your column supports null you can fix it like this: 如果您的列支持null,则可以按以下方式修复它:

        if (c == "0")
        {
            query += ", CitizenshipDate = NULL--instead of '0'";

If it does not support NULL values you will have to insert a default value such as DateTime.MinValue. 如果不支持NULL值,则必须插入默认值,例如DateTime.MinValue。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM