Question

I cannot use synomyms in my project because of some deployment restrictions so instead, I created this view:

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

It worked OK but now I need to modify it as follow:

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

Currently, it fails with:

Ambiguous column name 'Id'

in the LEFT OUTER JOIN line.

However, the Microsoft SQL Management Studio highlights [PersonalData].[dbo].[Titles] with the error:

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

In fact, it doesn´t provide me IntelliSense for that table's columns.

The table [PersonalData].[dbo].[Titles] is there. In fact, the following query returns results with no errors:

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

My knowledge about SQL is not deep enough but I don´t understand why this is, why it finds Users table but doesn´t find Titles.

A little more context:

  • The view that I am creating is not in the PersonalData database but in other database called Platform.
  • I checked the context and it is OK, I am creating the view in Platform database.

Why does it happen?

Was it helpful?

Solution 2

You need to add the table name to your [id] field. Because that field is in both tables that's why it's considered ambiguous (the view doesn't know which table to get it from).

SELECT u.[Id] AS [id] 

OTHER TIPS

The IntelliSense issue is peripheral, and it may be because of:

  1. the previous syntax error (you need to tell SQL Server which Id you mean, since it exists in both tables), or
  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.

Try

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

It appears that both your User table and your Titles tabe have a column named "Id". It's telling you that it doesn't know which Id column you mean in your SELECT column list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top