【问题标题】:Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query不允许从数据类型 datetime 到 int 的隐式转换。使用 CONVERT 函数运行此查询
【发布时间】:2012-09-07 10:57:31
【问题描述】:

alter table Garantor alter column [Birth Date] int

【问题讨论】:

    标签: sql-server-2008r2-express


    【解决方案1】:

    尝试这样的事情(您需要创建一个新列,使用转换更新它,删除旧列,然后用旧列重命名新列)

    ALTER TABLE dbo.Garantor
    ADD newBirthDate int NOT NULL DEFAULT 0 -- NULL and DEFAULT as required
    GO
    
    UPDATE dbo.Garantor
    SET newBirthDate = CAST([Birth Date] AS int) -- or CONVERT function, it will do the same
    GO
    
    ALTER TABLE dbo.Garantor
    DROP COLUMN [Birth Date]
    GO
    
    SP_RENAME 'dbo.Garantor.newBirthDate', 'dbo.Garantor.[Birth Date]'
    GO
    

    【讨论】:

    • 如果该列都是空的,你可以把它改成varchar再改成int。这会奏效。
    【解决方案2】:

    转换对我不起作用。 演员也不起作用。 要更改列的数据类型,下面是有效的代码。 将“date”类型更改为“int”类型,只保留年份。

    这对我有用:

    ALTER TABLE [dbo].[Garantor]
    ADD [newBirthDate] int NOT NULL DEFAULT 0
    GO
    
    UPDATE [dbo].[Garantor]
    SET [newBirthDate] = DATEPART(yyyy,[Birth Date])
    GO
    
    ALTER TABLE [dbo].[Garantor]
    DROP COLUMN [Birth Date]
    GO
    
    SP_RENAME 'dbo.Garantor.newBirthDate', 'dbo.Garantor.[Birth Date]'
    GO
    

    另一种解决方案是:

    = YEAR([Birth Date])
    

    如果你的表中有索引:

    ALTER TABLE [dbo].[Garantor]
    ADD [newBirthDate] int NOT NULL DEFAULT 0
    GO
    
    UPDATE [dbo].[Garantor]
    SET [newBirthDate] = DATEPART(yyyy,[Birth Date])
    GO
    
    ALTER TABLE [dbo].[Garantor] DROP CONSTRAINT [UQ__Garantor__1C123681D17FE31B] -- [UQ__Garantor__1C123681D17FE31B] change with your
    GO
    
    ALTER TABLE [dbo].[Garantor]
    DROP COLUMN [Birth Date]
    GO
    
    SP_RENAME 'dbo.Garantor.newBirthDate', 'dbo.Garantor.[Birth Date]'
    GO
    
    ALTER TABLE [dbo].[Garantor] ADD UNIQUE NONCLUSTERED 
    (
        [Birth Date] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
    GO
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    • 这是我对 Stackoverflow 的第一个回复。根据建议修改。好吧,我希望。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多