Miranda Johnson (6/17/2015)
the while loop creates the 12 digit random character string subtracting 1 from the@len variable in each iteration until it has all 12 characters
I will have to look into the use of SCOPE_IDENTITY
Ahh yes I see it now. You could do this with a tally table instead of a loop. I have a view on my system that is my tally table.
create View [dbo].[cteTally] as
WITH
E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
)
select N from cteTally
GO
This has millions of uses and has been referred to around here as "the swiss army knife of t-sql". You can read more about tally tables and there uses here. http://www.sqlservercentral.com/articles/T-SQL/62867/[/url]
If you are interested in using a tally table instead of a loop for this it might look something like this.
declare @n varchar(64)
DECLARE @Len int
SET @Len = 12
set @n='';
with RandomChars as
(
select top(@Len) char(n) as RandChar
from cteTally
where CHAR(n) not IN ('0', ':', ';', '`', '0', 'l', '1', '.', ',', '&', '=', '-', '(', ')', '[', ']', '?', '/', '\', '_', '''')
AND N > 32
AND N <= 122
order by NEWID()
)
select @n = @n + RandChar
from RandomChars
select @n
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/