is there an easy to use formula for switching the datatype on a table column from int to bit?

StackOverflow https://stackoverflow.com/questions/20908167

  •  24-09-2022
  •  | 
  •  

Question

I'm looking at a sql server table, and one of the columns seems to have been setup to be of type INT NULL when it's really better off as a BIT NOT NULL.

Is there an easy formula or shortcut for switching the type?


My current strategy is:

  • add new temp column
  • populate with data based on old column contents
  • drop old column and constraints
  • rename new column to old column name
  • add constraints based on new column

this seems complicated but, really, should be automatable - so i'm wondering if anyone's automated it yet.

Was it helpful?

Solution

Update MyTable set MyColumn = 0 where MyColumn is null

Assuming you want null to be false

Alter table MyTable alter column MyColumn bit not null

Will do the job, given all non-zero values are to be treated as true.

Course you were going to backup before you did any of this weren't you. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top