Domanda

We have a software designed to run on MS SQL 2005, we have upgraded the database to 2008 R2, and are trying to increase accuracy in our timestamp by using Datetime2 instead of Datetime. The software running is still unchanged, and will have the accuracy of Datetime. But there is a extra field updated with correct ms.

So my question is; Are there any best practice for a trigger that takes the datetime2, and replace the MS-part with the correct value? I was hoping to avoid the cup-demanding convert to string and back again but has not been able to find a good function for this.

È stato utile?

Soluzione

This seems to do the job:

create table T (ID int not null, Stamp1 datetime2 not null,
                RealMillis int not null);
go
create trigger TT on T
instead of insert
as
    set nocount on;
    insert into T(ID,Stamp1,RealMillis)
    select
        ID,
        DATEADD(millisecond,RealMillis - DATEPART(millisecond,Stamp1),Stamp1),
        RealMillis --or 0 now that it's been used?
    from inserted;
go
insert into T(ID,Stamp1,RealMillis) values (1,'2014-03-14T10:01:29.343',344);
go
select * from T;

I chose to do it as an instead of trigger since it avoids having to write the wrong data to the table in the first place.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top