'datetime2' error when using entity framework in VS 2010 .net 4.0

前端 未结 16 1278
半阙折子戏
半阙折子戏 2020-11-29 00:04

Getting this error:

System.Data.SqlClient.SqlException : The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range v

16条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 00:38

    Use that SQL script to convert all the columns from datetime to datetime2. It skips all the tables contains 'aspnet' for your convenience.

    DECLARE @SQL AS NVARCHAR(1024)
    DECLARE @TBL AS NVARCHAR(255)
    DECLARE @COL AS NVARCHAR(255)
    DECLARE @NUL AS BIT
    
    DECLARE CUR CURSOR FAST_FORWARD FOR
        SELECT  SCHEMA_NAME(t.schema_id)+'.'+t.name, c.name, c.is_nullable
        FROM    sys.tables AS t
        JOIN    sys.columns c ON t.object_id = c.object_id
        JOIN    information_schema.columns i ON i.TABLE_NAME = t.name 
                                            AND i.COLUMN_NAME = c.name
        WHERE   i.data_type = 'datetime' and t.name not like '%aspnet%'
    
        ORDER BY t.name, c.name
    
    OPEN CUR
    FETCH NEXT FROM CUR INTO @TBL, @COL, @NUL
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SELECT @SQL = 'ALTER TABLE ' + @TBL 
            + ' ALTER COLUMN [' + @COL + '] datetime2' 
            + (CASE WHEN @NUL=1 THEN '' ELSE ' NOT' END) + ' NULL;'
        EXEC sp_executesql @SQL
        FETCH NEXT FROM CUR INTO @TBL, @COL, @NUL
    END
    
    CLOSE CUR;
    DEALLOCATE CUR;
    

    It works for me!

提交回复
热议问题