try this , ill be interested to hear how it performs in comparison.
Note that the case statement on the call to GetRandomCode is required otherwise you will get the same value returned.
On my dev server it creates 15,000,000 rows in about 11 mins, cutting down the size of the union to your limited set should improve matters.
CREATE TABLE dbo.Numbers (Num INT NOT NULL PRIMARY KEY CLUSTERED);
GO
DECLARE @i INT;
SELECT @i = 1;
WHILE @i <= 10000
BEGIN
INSERT INTO dbo.Numbers(Num) VALUES (@i);
SELECT @i = @i + 1;
END;
Create View VwNewId
as
Select New_Id = newid()
go
Drop Function GetRandomCode
go
Create Function GetRandomCode(@CharsNeeded integer)
returns table
as
return
(
with cteCharsNeeded(Character)
as(
select '1' union all select '2' union all select '3' union all select '4' union all select '6' union all select '7' union all select '8' union all select '9' union all Select '0' union all
select 'A' union all select 'B' union all select 'C' union all select 'D' union all select 'E' union all select 'F' union all select 'G' union all select 'H' union all Select 'I' union all
select 'J' union all select 'K' union all select 'L' union all select 'M' union all select 'N' union all select 'O' union all select 'P' union all select 'Q' union all Select 'R' union all
select 'S' union all select 'T' union all select 'U' union all select 'V' union all select 'W' union all select 'X' union all select 'Y' union all select 'Z' union all
select 'a' union all select 'b' union all select 'c' union all select 'd' union all select 'e' union all select 'f' union all select 'g' union all select 'h' union all select 'i' union all
select 'j' union all select 'k' union all select 'l' union all select 'm' union all select 'n' union all select 'o' union all select 'p' union all select 'q' union all select 'r' union all
select 's' union all select 't' union all select 'u' union all select 'v' union all select 'w' union all select 'x' union all select 'y' union all select 'z'
),
ctenumbers(num)
as
(
Select Num from numbers
where Num <= @CharsNeeded
),
cteRandomChars(num,c)
as
(
select num,c = chars.c
from ctenumbers cross apply (select top 1 Character from cteCharsNeeded,vwNewId where num = num order by new_id) as chars(c)
)
select (
select c as [text()]
from cteRandomChars
for xml path('')) as Random
)
go
drop table #res
go
create table #res
(
random char(8)
)
insert into #res
select Random from sysobjects cross apply GetRandomCode(case when id is not null then 8 else null end)