WITH没有像我预期的那样工作sqlServer 2012

时间:2023-01-19 09:17:12

I am getting diferents results into a WITH statement. here is my first query:

我将差异结果变成了一个WITH语句。这是我的第一个查询:

with q as (select top (100000) * from table1) select * from q

用q作为(从表1中选择顶部(100000)*)从q中选择*

Let's say that table1 has an ID field, everything seems to be normal if I execute that query, it works as I expected. But if I change the statement like this:

假设table1有一个ID字段,如果我执行该查询,一切似乎都正常,它按照我的预期工作。但是,如果我改变这样的声明:

with q as (select top (100000) * from table1) select [ID] from q
or
with q as (select top (100000) * from table1) select q.[ID] from q

使用q as(从表1中选择顶部(100000)*)从q中选择[ID]或使用q作为(从表1中选择顶部(100000)*)从q中选择q。[ID]

it brings me results that does not exists into the first query (note that I only bring ID). I understand that WITH statement is a temporal result set an I expect that both queries brings the same result no matter how many fields I select, so why is this happening?, this could be a problem if i want to perform an update or even worst if I do a delete I will not be completely sure if I have affected the rows that I wanted

它给我带来了第一个查询中不存在的结果(注意我只带ID)。我理解WITH语句是一个时间结果集,我希望无论我选择多少个字段,两个查询都会得到相同的结果,为什么会发生这种情况?如果我想执行更新甚至最差,这可能是一个问题如果我删除,我将不能完全确定我是否影响了我想要的行

1 个解决方案

#1


4  

If you select top x without an order by, the result set is arbitrarily returned. Meaning you can get a different result set if you execute it twice. Since you are changing the query slightly, I'm not surprised the result set is different. Add an ORDER BY if you SELECT TOP x

如果选择没有顺序的前x,则任意返回结果集。这意味着如果执行两次,您可以获得不同的结果集。由于您稍微更改了查询,因此结果集不同,我并不感到惊讶。如果SELECT TOP x,请添加ORDER BY

#1


4  

If you select top x without an order by, the result set is arbitrarily returned. Meaning you can get a different result set if you execute it twice. Since you are changing the query slightly, I'm not surprised the result set is different. Add an ORDER BY if you SELECT TOP x

如果选择没有顺序的前x,则任意返回结果集。这意味着如果执行两次,您可以获得不同的结果集。由于您稍微更改了查询,因此结果集不同,我并不感到惊讶。如果SELECT TOP x,请添加ORDER BY