• DBA (5/5/2009)


    when creating a table we made a mistake it was supposed to be an integer column and is supposed to store by default a distributer ID using a function. (ftDistID:int,null)

    Okay, now this makes sense as to why you want to do it.

    Using the sample code you provided, I created this test:

    if object_id('tempdb..#Dates') is not null DROP TABLE #Dates

    CREATE TABLE #Dates (DateField datetime)

    insert into #Dates

    select '1900-01-30 00:00:00.000' union all

    select '1900-01-30 00:00:00.000' union all

    select '1900-03-04 00:00:00.000' union all

    select '1901-11-09 00:00:00.000' union all

    select '1901-11-09 00:00:00.000'

    select DateField, convert(int, DateField) from #Dates

    As you can see, just converting the field to an int is giving you the desired results.

    Based on this, you would think that you could just do this:

    ALTER TABLE "tablename" ALTER COLUMN "columnname" INTEGER

    if you try this, you will get this error:

    Msg 257, Level 16, State 3, Line 1

    Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query.

    So, you will have to add a new field to your table, populate it with the integer representation of your date field, and finally dropping the date field. My final code for showing all of this is:

    if object_id('tempdb..#Dates') is not null DROP TABLE #Dates

    CREATE TABLE #Dates (DateField datetime)

    insert into #Dates

    select '1900-01-30 00:00:00.000' union all

    select '1900-01-30 00:00:00.000' union all

    select '1900-03-04 00:00:00.000' union all

    select '1901-11-09 00:00:00.000' union all

    select '1901-11-09 00:00:00.000'

    select DateField, convert(int, DateField) from #Dates

    GO

    alter table #Dates add NewDateField INT

    GO

    update #Dates set NewDateField = convert(int, DateField)

    select * from #Dates

    GO

    alter table #Dates DROP COLUMN DateField

    GO

    select * from #Dates

    Of course, MAKE SURE that you try this out IN A TEST ENVIRONMENT. As "the keeper of the data", your first priority is retaining that accurate data that you do have. Only do this in production when you are sure you will get what you want.

    Wayne
    Microsoft Certified Master: SQL Server 2008
    Author - SQL Server T-SQL Recipes


    If you can't explain to another person how the code that you're copying from the internet works, then DON'T USE IT on a production system! After all, you will be the one supporting it!
    Links:
    For better assistance in answering your questions
    Performance Problems
    Common date/time routines
    Understanding and Using APPLY Part 1 & Part 2