2

由于一些部署限制,我不能在我的项目中使用同义词,所以相反,我创建了这个视图:

CREATE VIEW [dbo].[User] AS SELECT * FROM [PersonalData].[dbo].[User] 
GO

它工作正常,但现在我需要修改它如下:

ALTER VIEW [dbo].[User] AS 
    SELECT [Id],
    t.[Name] AS [Title],
    [FirstName],
    [LastName],
    [JobTitle],
    [Department],
    [EmailAddress],
    [PhoneNumber],
    [PhoneExtension],
    [MobilePhoneNumber],
    [CreatedDate],
    [ModifiedDate],
    [Uid],
    [Active]
    FROM [PersonalData].[dbo].[User] AS u
    LEFT OUTER JOIN [PersonalData].[dbo].[Titles] AS t ON u.TitleId = t.Id 
GO

目前,它失败了:

Ambiguous column name 'Id'

LEFT OUTER JOIN在行中。

但是,Microsoft SQL Management Studio 突出显示[PersonalData].[dbo].[Titles]错误:

Invalid object name '[PersonalData].[dbo].[Titles]

事实上,它并没有为我提供该表的列的 IntelliSense。

桌子[PersonalData].[dbo].[Titles]在那里。事实上,以下查询返回的结果没有错误:

select * from [PersonalData].[dbo].[Titles]

我对 SQL 的了解不够深入,但我不明白为什么会这样,为什么它找到Userstable 但没有找到Titles

更多上下文:

  • 我正在创建的视图不在PersonalData数据库中,而是在其他名为Platform.
  • 我检查了上下文,没关系,我正在Platform数据库中创建视图。

为什么会这样?

4

3 回答 3

6

IntelliSense 问题是外围问题,可能是因为:

  1. 前面的语法错误(你需要告诉 SQL Server你的意思,因为 Id存在于两个表中),或者
  2. that your local IntelliSense cache is stale. You can fix this by issuing Ctrl+Shift+R or using Edit > IntelliSense > Refresh Local Cache (and, depending on the network connection to the server, waiting seconds or even minutes).

That said, I would suggest two changes, one serious and one just a best practice:

  1. Don't name columns Id. The name is completely meaningless. Is it a UserID? Ok, call it UserID wherever it appears in the schema.
  2. Properly prefix all of the columns in your queries, not just the ones that have a name collision. This makes your query easier to understand and prevents people having to go manually figure out which table a column comes from.
于 2013-03-05T20:10:20.457 回答
3

您需要将表名添加到您的[id]字段中。因为该字段在两个表中,所以它被认为是模棱两可的(视图不知道从哪个表中获取它)。

SELECT u.[Id] AS [id] 
于 2013-03-05T19:56:38.953 回答
1

尝试

ALTER VIEW [dbo].[User] AS 
    SELECT u.[Id],

您的用户表和标题选项卡似乎都有一个名为“Id”的列。它告诉您它不知道您在 SELECT 列列表中指的是哪个 Id 列。

于 2013-03-05T19:19:10.570 回答