-4

alter table Garantor alter column [Birth Date] int

Burak KÜKRER
  • 69
  • 2
  • 6

2 Answers2

3

Try something like this (you'll need to create a new column, update it with a conversion, drop the old one then rename the new one with old one's name)

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
Ian Grainger
  • 5,148
  • 3
  • 46
  • 72
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • If the column are all nulls, you can change it to varchar then change it to int. That will work. – Zath Jul 11 '14 at 12:46
1

Convert does not work for me. Cast does not work either. To change the data type of a column, here is the code that worked. Change the "date" type to the "int" type, keeping only the year.

This works for me:

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

An alternative solution is:

= YEAR([Birth Date])

And if you have an index in your table:

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
ufo
  • 674
  • 2
  • 12
  • 35
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 18 '21 at 11:14
  • 1
    This was my first response on Stackoverflow. Modified according to recommendations. Well, I hope. – warmichlive Nov 18 '21 at 12:15