Delete table columns during storage

Source: Internet
Author: User

When dynamically creating a database table field, if the "empty" attribute of this field is not empty, and the table is associated with other tables, deleting the column dynamically may fail. The error is reported because one or more objects access this column. The solution is to first Delete the constraint on the column and then delete the column!

The stored procedure is as follows:

Create procedure pr_deltablerow
@ Tablename varchar (100), @ datafieldname varchar (100)
As

Begin tran

Declare @ sqldel varchar (500), @ df_name varchar (500)

Set @ sqldel =''
/* Determine whether the Column exists */
If exists (select 1 from syscolumns where id = object_id (@ tablename) and name = @ datafieldname)
Begin
/* Query the constraints of this column */
Select @ df_name = Name from sysobjects where xtype = 'D' and parent_obj = object_id (@ tablename) and exists (select * From syscolumns where id = object_id (@ tablename) and info = colid and name = @ datafieldname)
/* Delete the constraint of this column */
Set @ sqldel = 'alter table' + @ tablename + 'drop constraint' + @ df_name
Exec (@ sqldel)
 
/* Now this column is available */
Set @ sqldel = 'alter table' + @ tablename + 'drop column' + @ datafieldname
Exec (@ sqldel)
End

If (@ error = 0)

Commit tran

Else

Rollback tran

 

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.