Change Date Time Fields to Support Second-Level Precision

<< Click to Display Table of Contents >>

Navigation:  Database > Modifications >

Change Date Time Fields to Support Second-Level Precision

This article refers to EQuIS Databases in Microsoft SQL Server.

 

Many tables in the EQuIS Database include columns for date and time data. Microsoft SQL Server supports these data types for date and time data:

datetime2: 6 bytes per value stored, and has a range of 0001-01-01 to 9999-12-31, with precision of 1/100 of a second.

smalldatetime: 4 bytes per value stored, ranging from January 1, 1900 through June 6, 2079, with accuracy to the minute.

 

By default, the EQuIS Database uses smalldatetime because it is more efficient and meets most needs. In some situations, users need additional levels of precision. Any date or time field in EQuIS may be changed from smalldatetime to datetime2 to enable data storage with second-level precision.

 

Change Date and/or Time Data Types

 

1.Start SQL Server Management Studio.

2.Log into and select the desired database.

3.Select New Query.

4.Paste the following script in the SQLQuery window, with the appropriate table name and column name.

alter table <table_name>
alter column <column_name> datetime2(2)
 
For example, see this script for DT_SAMPLE:

 
alter table DT_SAMPLE
alter column SAMPLE_DATE datetime2(2)

 

5.Click Execute.

 

Note: Database owner or administrator privileges are required in order to make database changes. Always backup the entire database before making any changes.

 

Troubleshooting

 

Attempting to modify the data type of a column that is part of an index or constraint may fail as follows:

 

ALTER TABLE ALTER COLUMN xxxxxx failed because one or more objects access this column.

 

Remove the index and/or constraint to make the change, then restore it after the column has been modified. For example, suppose the user wants to modify DT_TEST.ANALYSIS_DATE to be datetime2. If ANALYSIS_DATE is part of the TestAlternateKey, then drop the TestAlternateKey constraint and recreate it as follows:

 

   -- drop the existing TestAlternateKey
   if exists (select name from sysindexes where name = 'TestAlternateKey')
     alter table [dbo].[dt_test] drop constraint TestAlternateKey
   go
 
   -- change analysis_date to datetime2
   alter table [dbo].[dt_test] alter column analysis_date datetime2(2) null
   go
 
   -- restore TestAlternateKey
   -- NOTE:  comment any fields that are not included in your TestAlternateKey
   alter table [dbo].[dt_test] add  constraint TestAlternateKey unique nonclustered
   (
    [facility_id]
   ,[sample_id]
   ,[analytic_method]
   ,[analysis_date]
   ,[test_type]
   ,[fraction]
 
 
   ,[column_number]
   )
   go

 

Note: The auto-populate feature will populate the system date when it is a required column.