向 SQL 视图添加主键

2021-09-10 00:00:00 sql tsql sql-server

我在 SQL Server 数据库中创建了一个视图,它只是两个表的连接.

I have created a view in a SQL Server database which is just a join of two tables.

有什么办法可以在这个视图的行中插入一个唯一的主键……或者我不确定如何将其中一个列名指定为主键……有什么想法吗?

Is there any way I can insert a unique primary key into the rows of this view ...or I'm not sure how I can specify one of the column names to be a primary key...any ideas?

谢谢

推荐答案

您必须创建物化(索引)视图才能添加唯一索引.但是你不能创建PK约束.

You would have to create materialized (indexed) view in order to be able to add unique index. But you can't create PK constraint.

CREATE VIEW v_test
WITH SCHEMABINDING --optional
AS
    SELECT id from table

GO

CREATE UNIQUE CLUSTERED INDEX idx_id
    ON v_test (id)
GO

相关文章