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
  •  | 
  •  

문제

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.

도움이 되었습니까?

해결책

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. :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top