Delete the default value of a column in the SQL Server database table

Source: Internet
Author: User

In SQL Server, if the default value is set for a field in the table, a default constraint is generated in the system table sysobjects.
If you want to perform operations on the field with the default value, such as changing the column type and deleting the column, an error is reported. Therefore, before performing operations on this field, you can use the following script to delete the default value:

Declare @ tablename varchar (100), @ columnname varchar (100), @ tab varchar (100) set @ tablename = 'table name' set @ columnname = 'field name' declare @ defname varchar (100) Declare @ cmd varchar (100) select @ defname = Name from sysobjects a join sysconstraints SC on. id = SC. constid where object_name (. parent_obj) = @ tablename and. xtype = 'D' and SC. colid = (select colid from syscolumns where id = object_id (@ tablename) and name = @ columnname) select @ cmd = 'alter table' + @ tablename + 'drop constraint' + @ defname if @ CMD is null print 'No Default constraint to drop' exec (@ cmd)
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.