【发布时间】:2011-05-27 17:28:09
【问题描述】:
我有一个问题,为什么这两个查询的输出不同。我本来希望它们能以同样的方式工作。
查询 1:
declare @cache table(originalValue nvarchar(255), obfuscateValue nvarchar(255));
declare @table1 table(c char(1));
declare @i1 int;
set @i1 = ASCII('0');
while @i1 <= ASCII('9')
begin
insert into @table1 (c)
select (CHAR(@i1))
set @i1 = @i1 +1;
end
insert into @cache (originalValue, obfuscateValue)
select [firstname],
(select top 1 c from @table1 order by NEWID()) +
(select top 1 c from @table1 order by NEWID())
from Customer
where [firstname] is not null
select * from @cache;
查询 2:
declare @cache table(originalValue nvarchar(255), obfuscateValue nvarchar(255));
declare @table1 table(c char(1));
declare @i1 int;
set @i1 = ASCII('0');
while @i1 <= ASCII('9')
begin
insert into @table1 (c)
select (CHAR(@i1))
set @i1 = @i1 +1;
end
insert into @cache (originalValue)
select [firstname]
from Customer
where [firstname] is not null
update c
set c.obfuscateValue = t.Value
from @cache c
join
(
select originalValue,
(
(select top 1 c from @table1 order by NEWID()) +
(select top 1 c from @table1 order by NEWID())
) as Value
from @cache
) t on t.originalValue = c.originalValue
select * from @cache;
他们应该做同样的事情,但第一个查询返回以下结果:
Jonathon 73
Everett 73
Janet 73
Andy 73
Shauna 73
第二个:
Jonathon 82
Everett 40
Janet 68
Andy 79
Shauna 29
如您所见,第二个结果中的第二列具有不同的值,而第一列具有相同的值。
看起来在第一次查询中
(select top 1 c from @table1 order by NEWID()) +
(select top 1 c from @table1 order by NEWID())
只调用一次。
谁能解释一下这个谜团?
【问题讨论】:
-
这可能解释了一些事情stackoverflow.com/questions/1468159/…
-
您只是想生成一个介于 00 和 99 之间的数字吗?还是别的什么?
-
不,这是一个例子。它应该适用于任何策略,例如 000-999999。
标签: sql-server tsql sql-server-2008