3

Could be different the way sql server gets the current time and the way the c# compiler gets it??

I have a trigger in a sql server table, where in each update the updateDatetime column will be updated to the current date time.

I get this current date time with current_timestamp

I have also a c# code which connects to this database and using native sql updates the table, after this the trigger will be created.

The thing is that I am running a test in NUnit where I do an update, and then I retrieve the altered row. If I compare the updatedDatetime with the current one at the beginning of the test they are different. I do this with DateTime.UtcNow

The difference it's just by milliseconds, but the funny thing is that the one from the beginning of the test happens after the one from the trigger! Which it makes no sense.

Here some code to illustrate what I am saying

                DateTime dateTimeBefore = DateTime.UtcNow;

                // Act
                bookDao.Update(book);

                // Assert
                alteredBook = bookDao.GetByKey(bookingDao);


                Console.WriteLine("dateTimeBefore: {0} - {1}", dateTimeBefore, dateTimeBefore.Millisecond);
                Console.WriteLine("UpdateDateTime: {0} - {1}", alteredBook.UpdatedDateTime, alteredBook.UpdatedDateTime.Millisecond);

                Assert.IsTrue(alteredBook.UpdatedDateTime >= dateTimeBefore);

this would be the trigger

update Book set UpdatedDatetime = current_timestamp from inserted where inserted.Id = Booking.Booking.Id

4

1 回答 1

1

current_time “源自运行 SQL Server 实例的计算机的操作系统”,datetime.now 也是如此。如果您的单元测试在 nunit 和您的 sql server 实例在另一台机器上运行的机器上运行,则这两个值的比较结果取决于每台机器的本地时间设置。

而且,此外,即使在同一台机器上,两个值(sql server datetime 类型的 current_timestamp 和 datetime.now)具有不同的精度 -从 DateTime 转换为 SqlDateTime 是不准确的

于 2012-11-28T12:54:00.653 回答