SQL 内部连接问题 - SQL71508 错误。试图内部连接两个表

SQL Inner Join troubles - SQL71508 Error. Trying to innner join two tables

我想通过一个视图来测试 table Items 上的访问权限,该视图将实现代码当前为单租户的多租户操作。

所以我将 Items 重命名为 _Items 并着手创建一个名为 Items 的视图。如果我做一个简单的

SELECT * FROM _Items 

它有效,而且代码 none 更明智。然后我尝试将项目 table 与用户 table 结合起来,这样我就可以通过视图测试多租户访问,但是我收到了一个我不明白的错误。

这里是查询:

CREATE VIEW [dbo].[Items] 
AS 
    SELECT * 
    FROM _Items I 
    INNER JOIN Users U ON I.TenantId = U.TenantId
    WHERE U.UserName = SUSER_SNAME()

SELECT * FROM 中的星号被标记,悬停在它上面会产生:

SQL71508 :: The model already has an element that has the same name dbo.Items.Id.

在 VS2017 中单击更新会为每一列产生相同的错误。

SQL71508 :: The model already has an element that has the same name dbo.Items.Id.

SQL71508 :: The model already has an element that has the same name dbo.Items.Id.

SQL71508 :: The model already has an element that has the same name dbo.Items.Active.

SQL71508 :: The model already has an element that has the same name dbo.Items.TenantId.

SQL71508 :: The model already has an element that has the same name dbo.Items.Active.

SQL71508 :: The model already has an element that has the same name dbo.Items.TenantId.

我做错了什么?

TIA

您尝试创建的 VIEW 似乎已经存在。使用 CREATE OR ALTER VIEW 而不是 CREATE VIEW 来覆盖它。

如果您只想让您的视图包含 _Items 中的列,按用户筛选,请尝试

CREATE OR ALTER VIEW [dbo].[Items] AS 
SELECT I.* FROM _Items I INNER JOIN Users U
    ON I.TenantId = U.TenantId
WHERE U.UserName = SUSER_SNAME()

您的 SQL 将获取 Users 和 _Items 的所有列,并且您肯定至少有一个列在它们之间具有相同的名称,即 TennantId,即您要加入的列。