简体   繁体   English

SQL 服务器不同的方式掉一列

[英]SQL Server different ways to drop a column

I've created a column called "Identified" and I've assigned a default value of "1".我创建了一个名为“已识别”的列,并分配了一个默认值“1”。 Now I realized that I would like to delete that column.现在我意识到我想删除该列。 But when I try I get the following error:但是当我尝试时,我收到以下错误:

Msg 5074, Level 16, State 1, Line 5消息 5074,第 16 级,State 1,第 5 行
The object 'DF__orders__Identifi__403A8C7D' is dependent on column 'Identified'. object 'DF__orders__Identifi__403A8C7D' 取决于列 'Identified'。

Msg 4922, Level 16, State 9, Line 5消息 4922,第 16 级,State 9,第 5 行
ALTER TABLE DROP COLUMN Identified failed because one or more objects access this column. ALTER TABLE DROP COLUMN 识别失败,因为一个或多个对象访问此列。

Here is the code used:这是使用的代码:

ALTER TABLE BikeStores.sales.orders 
    DROP COLUMN Identified;

I've also tried:我也试过:

ALTER TABLE BikeStores.sales.orders 
    DROP Identified;

But in this case the error get is:但在这种情况下,错误得到的是:

Msg 3728, Level 16, State 1, Line 5消息 3728,第 16 层,State 1,第 5 行
'Identified' is not a constraint. “已识别”不是约束。

Msg 3727, Level 16, State 0, Line 5消息 3727,第 16 级,State 0,第 5 行
Could not drop constraint.无法删除约束。 See previous errors.请参阅以前的错误。

Any tip on how to fix this error?有关如何解决此错误的任何提示? Thanks in advance提前致谢

The column cannot be dropped because the default constraint is dependant on the column existing.无法删除该列,因为默认约束依赖于现有的列。 Drop the default constraint first.首先删除默认约束。

If the version of SQL server you are working with is 2016 or before you can use the simple query:如果您正在使用的 SQL 服务器的版本是 2016 或之前的版本,您可以使用简单查询:

ALTER TABLE BikeStores.sales.orders ALTER COLUMN Identified DROP DEFAULT;

From 2017 onwards you will need to explicitly use the default constraints name从 2017 年起,您将需要明确使用默认约束名称

ALTER TABLE BikeStores.sales.orders DROP CONSTRAINT DF__orders__Identifi__403A8C7D;

If you do not know the name of the default (due to it being auto named on creation) the following script will identify and remove the default.如果您不知道默认值的名称(由于它在创建时自动命名),以下脚本将识别并删除默认值。

declare @schema_name nvarchar(256)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
declare @Command  nvarchar(1000)

set @schema_name = N'sales'
set @table_name = N'orders'
set @col_name = N'Identitified'

select @Command = 'ALTER TABLE ' + @schema_name + '.[' + @table_name + '] DROP CONSTRAINT ' + d.name
 from sys.tables t
  join sys.default_constraints d on d.parent_object_id = t.object_id
  join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
 where t.name = @table_name
  and t.schema_id = schema_id(@schema_name)
  and c.name = @col_name

EXEC sp_executesql @Command

(credit to this question for the last part ) How to drop SQL default constraint without knowing its name? (最后一部分归功于这个问题) 如何在不知道其名称的情况下删除 SQL 默认约束?

You will then be able to drop your column然后,您将能够删除您的列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM