Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Alter Column in table From Bit to Int

So What I am looking to do is alter a table and change a column from an BIT to INT. Although currently in the column there are null values I would like to change to -1 and not allow null. Since BIT only holds 0 and 1, how would I Alter the Column to an INT and Set the Null values to -1

I was thinking something along the lines of

ALTER TABLE TABLENAME
ALTER COLUMN COLUMNAME INT SET DEFAULT -1
WHEN NULL THEN CAST(-1 AS INT)
like image 531
x Nuclear 213 Avatar asked Jun 25 '14 19:06

x Nuclear 213


People also ask

Can alter table change data type?

We can use ALTER TABLE ALTER COLUMN statement to change the datatype of the column. The syntax to change the datatype of the column is the following. In the syntax, Tbl_name: Specify the table name that contains the column that you want to change.

How do you change the datatype of a column in SQL using cast?

Data_Type is the target data type to which you want to convert the expression/value. Length is an integer value that specifies the length of the target type. For example; VARCHAR(50) Expression/Value is what you want converted into the desired data type.

How do I change the size of a column in SQL?

In generic terms, you use the ALTER TABLE command followed by the table name, then the MODIFY command followed by the column name and new type and size. Here is an example: ALTER TABLE tablename MODIFY columnname VARCHAR(20) ; The maximum width of the column is determined by the number in parentheses.


2 Answers

Hope the following code snippet will help you out.

--Created table for testing
CREATE TABLE Test(COl Bit)

--Insertint values
INSERT INTO Test VALUES(0)
INSERT INTO Test VALUES(NULL)
INSERT INTO Test VALUES(1)

--Change the column type
ALTER TABLE Test ALTER COLUMN COL INT

-- Update null values to -1
UPDATE Test SET COL = ISNULL(COL,-1) WHERE COL is NULL

-- Changing the column to not null
ALTER TABLE Test ALTER COLUMN COL int NOT NULL
like image 53
classic_vmk Avatar answered Oct 03 '22 08:10

classic_vmk


proper Syntax is:

ALTER TABLE {TABLENAME} 
ALTER {COLUMNNAME} {TYPE} {NULL|NOT NULL} 
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}

Do it step by step as shown below

create table test2(id int not null identity primary key ,
 col bit);


ALTER TABLE test2
ALTER COLUMN col INT NULL --Alter to change the type to INT

alter table test2
add constraint dflt default -1 for col  --Alter to create a default value
like image 29
Rahul Avatar answered Oct 03 '22 07:10

Rahul