Modifying default values for SQL Server database-related fields

Source: Internet
Author: User
Tags join table name

The original database has many types of data default values are null values, for later in the actual development process with a lot of unchanged. This null is actually good, I think can save the database space, in the new data can also improve the speed. However, the following code should be written at the request of the leader. Done with the help of Csdn's heroes.

Declare @t table (ID int identity (1,1), Tbname varchar (256), colname varchar (256), xtype varchar (20))

INSERT INTO @t

Select A.name,b.name, C.name

From sysobjects a

INNER JOIN syscolumns B on a.id=b.id

INNER JOIN systypes c on b.xusertype = C.xusertype

where a.xtype= ' u '

and c.name in (' varchar ', ' int ')

and b.status<>0x80--remove self-adding columns

And not exists--filters out columns that already have default values

(SELECT 1

From

(SELECT

(select name from sysobjects where id=c.id) table name,

(select name from syscolumns where cdefault=a.id) field name

From sysobjects B,syscolumns c,syscomments a

where b.xtype= ' d '

and A.id=b.id

and B.parent_obj=c.id

and A.colid=c.colid

) T

where a.name=t. Table name

and b.name=t. Field name)

--select * from @t

DECLARE @i int

Set @i=1

DECLARE @tbname varchar (256), @colname varchar (256), @xtype varchar, @sql nvarchar (4000)

While @i <= (select MAX (ID) from @t)

Begin

Select @tbname =tbname, @colname =colname, @xtype = Xtype from @t where id=@i

Set @sql = ' ALTER TABLE [' + @tbname + '] add constraint ' + ' df_ ' + replace (@tbname, '-', ') + ' _ ' + replace (@colname, '-', ') + ' Default '

If @xtype = ' int '

Begin

Set @sql = @sql + ' 0 '

End

else if @xtype = ' varchar '

Begin

Set @sql = @sql + ' "'

End

Set @sql = @sql + ' for [' + @colname + '] '

EXEC (@sql)

Set @i = @i + 1

End

Xiao Kee

After registering a good basic has not come, later will be the point of their own learning are recorded here. Record your own growth.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.