I have a question on why the output of these two queries differ. I would have expected them to work the same.
Query 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;
Query 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;
They should do the same, but first query returns following results:
Jonathon 73
Everett 73
Janet 73
Andy 73
Shauna 73
And second:
Jonathon 82
Everett 40
Janet 68
Andy 79
Shauna 29
As you noticed, the second column in second result has different values, while first - same values.
It looks like in first query the
(select top 1 c from @table1 order by NEWID()) +
(select top 1 c from @table1 order by NEWID())
is called only once.
Can someone explain this mystery?