Adding in a primary key to an SQL view

2019-09-02 08:12发布

问题:

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?

Thanks

回答1:

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