查看结果与查询的相同代码不同
我有一个带有一个内部联接查询的简单选择。但是,当我使用相同的代码创建视图时,结果是不同的。我不会从视图中提取数据。它都是基于用户表的。
查询:
SELECT DISTINCT TOP 100
dbo.table1.a1,
dbo.table1.a2,
dbo.table2.something_else FROM dbo.table1 inner join
dbo.table2 ON
dbo.tabel1.a1 = dbo.table2.somethingelse
WHERE dbo.table.a2 = '1'
ORDER BY dbo.table.a1 DESC
视图:
CREATE VIEW TEST
AS
SELECT DISTINCT TOP 100
dbo.table1.a1,
dbo.table1.a2,
dbo.table2.something_else FROM dbo.table1 inner join
dbo.table2 ON
dbo.tabel1.a1 = dbo.table2.somethingelse
WHERE dbo.table.a2 = '1'
ORDER BY dbo.table.a1 DESC
当我将查询的结果与视图进行比较时,它们似乎不同。 VIEW 的结果比查询多,而且顺序不一样(因为 VIEW 中的记录比查询多)。代码相同,怎么会不同呢?
I have a simple select with one inner join query. However when I create a view with the same code, the results are different. I am not pulling data from views. It is all user table based.
QUERY:
SELECT DISTINCT TOP 100
dbo.table1.a1,
dbo.table1.a2,
dbo.table2.something_else FROM dbo.table1 inner join
dbo.table2 ON
dbo.tabel1.a1 = dbo.table2.somethingelse
WHERE dbo.table.a2 = '1'
ORDER BY dbo.table.a1 DESC
VIEW:
CREATE VIEW TEST
AS
SELECT DISTINCT TOP 100
dbo.table1.a1,
dbo.table1.a2,
dbo.table2.something_else FROM dbo.table1 inner join
dbo.table2 ON
dbo.tabel1.a1 = dbo.table2.somethingelse
WHERE dbo.table.a2 = '1'
ORDER BY dbo.table.a1 DESC
When I compare the results of the Query to the View, they appear to be different. The VIEW has more result then the query and the order is not the same (due to more records in the VIEW than query.) Its the same code, so how can it be different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,在视图创建中不允许使用
ORDER BY
及相关语句。简而言之,结果以未定义的顺序从视图返回。这可能就是为什么您也不限制前 100 行,因为这些行没有排序。将您的排序和行计数提取到从视图中选择的语句中,然后看看是否有效。
Generally speaking,
ORDER BY
and related statements are not allowed in view creation. Simply put, the results are returned in an undefined order from a view. This is probably why you're also not restricting to the top 100 rows, because the rows aren't ordered.Pull out your ordering and rowcount into the statement that selects from the view, and see if that works.
我假设您正在谈论此查询:
在这种情况下,
SQL Server
只是在运行视图时优化掉ORDER BY
部分。您应该将其显式添加到调用视图的查询中:
I'm assuming you're talking about this query:
In this case,
SQL Server
just optimizes away theORDER BY
part when running the view.You should explicitly add it to the query that calls the view: