我可以在 SSMS 查询选项卡中编写此内容:
SELECT TOP (100) PERCENT ISBN AS ISBN, Title AS Title
FROM dbo.tBook
ORDER BY Title, ISBN
如果我将其写为“创建 View ”:
CREATE VIEW vBook1
AS
SELECT TOP (100) PERCENT ISBN AS ISBN, Title AS Title
FROM dbo.tBook
ORDER BY Title, ISBN
SSMS 将创建 View 但是它会删除别名,我猜是因为别名与表列相同?
当然,我可以使用不同的别名并将其保存在 View 中:
CREATE VIEW vBook1
AS
SELECT TOP (100) PERCENT ISBN AS ISBNx, Title AS Titlex
FROM dbo.tBook
ORDER BY Title, ISBN
我想使用原始名称为存储 View 中的名称添加别名以保持一定的一致性,但如果基础表列名称确实发生更改, View 的用户将不必编辑其代码。
最佳答案
评论有点长。你说:
if the underlying table column names do change, the users of the view won't have to edit their code
嗯,这确实是事实。如果基础列名称发生更改,则 View 将失效。该代码将不再起作用。无论如何,您都需要重新创建 View 。
如果您想确保列名称,您可以使用列名称显式创建 View :
Create view vBook1 (ISBN, Title) AS
SELECT ISBN, Title
FROM dbo.tBook;
我一般不太喜欢这种方法——在为 View 添加或重新排列列名称时,它可能会造成严重破坏。但你可能会感激它。
请注意,我删除了 ORDER BY
和 TOP 100 PERCENT
。这些都是让 SQL Server 编译器接受 ORDER BY 的技巧。这并不意味着 View 保证按任何特定顺序排列。
这在documentation中有非常明确的解释。 :
Important
The ORDER BY clause is used only to determine the rows that are returned by the TOP or OFFSET clause in the view definition. The ORDER BY clause does not guarantee ordered results when the view is queried, unless ORDER BY is also specified in the query itself.
关于sql - 为什么在存储为 View 时,与列名相同的别名会被删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975521/