2

I got a database with 200 plus tables.

Now I need a SQL script to find & convert all "nullable Int" to "nonnullable Int" columns (assume database is empty).

I know it can be done manually one by one

ALTER TABLE myTable 
ALTER COLUMN myColumn {DataType} NOT NULL DEFAULT(0)

But I think there should be better way to do this, and it will be great help if you can suggest one.

Moon
  • 33,439
  • 20
  • 81
  • 132
10K35H 5H4KY4
  • 1,496
  • 5
  • 19
  • 41

3 Answers3

3

Use this SQL:

DECLARE @TableName NVARCHAR(255)
DECLARE @ColumnName NVARCHAR(255)

DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD
FOR SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = 'dbo' AND IS_NULLABLE = 'YES' AND DATA_TYPE = 'int'
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @TableName, @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
    ALTER TABLE @TableName ALTER COLUMN @ColumnName INT NOT NULL DEFAULT(0)
    FETCH NEXT FROM @Cursor INTO @TableName, @ColumnName
END
CLOSE @Cursor
DEALLOCATE @Cursor
Moon
  • 33,439
  • 20
  • 81
  • 132
  • Thanks for your suggestion. Is there any way, that I just provide a database name and get all nullable int coulmn in all tables get Altered? – 10K35H 5H4KY4 Nov 17 '15 at 05:42
  • @DCODE: The SQL statement `SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND IS_NULLABLE = 'YES' AND DATA_TYPE = 'int'` does exactly that! – Moon Nov 17 '15 at 05:44
  • Thanks really appreciated that. – 10K35H 5H4KY4 Nov 17 '15 at 05:49
0

Oops...


https://msdn.microsoft.com/ja-jp/library/ms190273.aspx

NULL | NOT NULL

If the new column does not allow null values and the table is not empty, a DEFAULT definition must be added with the new column, and the new column automatically loads with the default value in the new columns in each existing row

and also you can see...

Add a column with a default value to an existing table in SQL Server

Cheers!

Community
  • 1
  • 1
MARK
  • 1
0

No. You can add multiple columns, but you have to use a separate alter table statement for each column you want to alter.

For Reference, See the ALTER TABLE syntax here http://msdn.microsoft.com/en-US/library/ms190273.aspx

Bhanu Chandra
  • 408
  • 8
  • 26