通过 alter table 命令删除 T-SQL 中的约束 - 问题

Removing a constraint in T-SQL by alter table command - problem(通过 alter table 命令删除 T-SQL 中的约束 - 问题)
本文介绍了通过 alter table 命令删除 T-SQL 中的约束 - 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 t-SQL 中有以下代码:

I have got the following code in t-SQL:

alter table Persons
drop primary key;

还有消息:消息 156,级别 15,状态 1,第 10 行关键字primary"附近的语法不正确.

我检查了不同的语法组合,但都没有奏效.这里有什么问题?

I have checked different combinations of syntax and none have worked. What is wrong here?

表格就是这样创建的 - 这只是学习的开始,非常简单,只有两个约束.

This is how a table has been created - it is just beggining of studying, so very simple one with only two constraints.

create table Persons(
PersonID int not null primary key,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

推荐答案

不是DROP PRIMARY KEY,而是DROP CONSTRAINT {Object Name}.例如:

CREATE TABLE dbo.YourTable (ID int NOT NULL);
GO
ALTER TABLE dbo.YourTable ADD CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED (ID);
GO
ALTER TABLE dbo.YourTable DROP CONSTRAINT PK_YourTable;
GO
DROP TABLE dbo.YourTable;

这就是为什么显式命名您的对象如此重要的原因,如上所示,因为您现在不知道 CONSTRAINT 的名称是什么.但是,您可以通过以下方式获取名称:

This is why it's so important to explicitly name your objects, as shown above, as you now don't know what the name of the CONSTRAINT is. You could, however, get the name with the following:

SELECT kc.[name]
FROM sys.key_constraints kc
     JOIN sys.tables t ON kc.parent_object_id = t.object_id
     JOIN sys.schemas s ON t.schema_id = t.schema_id
WHERE s.[name] = N'dbo'
  AND t.[name] = N'YourTable'
  AND kc.[type] = 'PK';

如果你真的不想找出名字然后写语句,你可以使用动态语句:

If you really didn't want to find out the name and then write the statement, you could use a dynamic statement:

DECLARE @SQL nvarchar(MAX);
SET @SQL = (SELECT N'ALTER TABLE ' + QUOTENAME(s.[name]) + N'.' + QUOTENAME(t.[name]) + N' DROP CONSTRAINT ' + QUOTENAME(kc.[name]) + N';'
            FROM sys.key_constraints kc
                 JOIN sys.tables t ON kc.parent_object_id = t.object_id
                 JOIN sys.schemas s ON t.schema_id = t.schema_id
            WHERE s.[name] = N'dbo'
              AND t.[name] = N'YourTable'
              AND kc.[type] = 'PK');
EXEC sys.sp_executesql @SQL;

这篇关于通过 alter table 命令删除 T-SQL 中的约束 - 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)