Using tsql I want to count a numeric chars in string. For example i've got 'kick0my234ass' string and i wanna count how many (4 in that example) numbers are in that string. I can't use regex, just plain tslq.
You COULD do this I suppose:
declare #c varchar(30)
set #c = 'kick0my234ass'
select #c, len(replace(#c,' ','')) - len(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(#c,'0',''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''),'8',''),'9',''),' ',''))
You'll first have to split the character string in its individual characters, evaluate which are numeric, and finally count those that are. This will do the trick:
DECLARE #test TABLE (Example NVARCHAR(255))
INSERT #test
VALUES ('kick0my234ass')
SELECT COUNT(1)
FROM #test AS T
INNER JOIN master..spt_values v
ON v.type = 'P'
AND v.number < len(T.Example)
WHERE SUBSTRING(T.Example, v.number + 1, 1) LIKE '[0-9]'
You could try this solution with regular expressions (if you'd allow them):
it uses recursive CTE, at every recursive step, one digit is removed from given string and the condition is to stop, when there are no digits in string. The rows are also numbered with consecutive ids, so the last id is the amount of removed digits from string.
declare #str varchar(100) = 'kick0my123ass';
with cte as (
select 1 [id], stuff(#str,PATINDEX('%[0-9]%', #str),1,'') [col]
union all
select [id] + 1, stuff([col],PATINDEX('%[0-9]%', [col]),1,'') from cte
where col like '%[0-9]%'
)
--this will give you number of digits in string
select top 1 id from cte order by id desc
Use a WHILE loop to each each character is a numeric or not.
Query
declare #text as varchar(max) = 'kick0my234ass';
declare #len as int;
select #len = len(#text);
if(#len > 0)
begin
declare #i as int = 1;
declare #count as int = 0;
while(#i <= #len)
begin
if(substring(#text, #i, 1) like '[0-9]')
set #count += 1;
set #i += 1;
end
print 'Count of Numerics in ' + #text + ' : ' + cast(#count as varchar(100));
end
else
print 'Empty string';
If simplicity & performance are important I suggest a purely set-based solution. Grab a copy of DigitsOnlyEE which will remove all non-numeric characters. Then use LEN against the output.
DECLARE #string varchar(100) = '123xxx45ff678';
SELECT string = #string, digitsOnly, DigitCount = LEN(digitsOnly)
FROM dbo.DigitsOnlyEE(#string);
Results
string digitsOnly DigitCount
------------------ ----------- ------------
123xxx45ff678 12345678 8
using a Tally Table created by an rCTE:
CREATE TABLE #Sample (S varchar(100));
INSERT INTO #Sample
VALUES ('kick0my234 ass');
GO
WITH Tally AS(
SELECT 1 AS N
UNION ALL
SELECT N + 1
FROM Tally
WHERE N + 1 <= 100)
SELECT S.S, SUM(CASE WHEN SUBSTRING(S,T.N, 1) LIKE '[0-9]' THEN 1 ELSE 0 END) AS Numbers
FROM #Sample S
JOIN Tally T ON LEN(S.S) >= T.N
GROUP BY S.S;
For future reference, also post your owns attempts please. We aren't here (really) to do your work for you.
I'm troubleshooting some strangeness in output of my SQL Server when I want to get records that are not null or empty string:
SELECT myString
FROM myTable
WHERE myString IS NOT NULL OR myString != ''
In addition to records that obviously fit (string values returned to SSMS's grid) I'm seeing records where the grid cell is blank. When I select the cell and try to copy it, my clipboard manager (clipmate.com) complains that the data is invalid.
If I output the query to file instead of to grid and then inspect via Hex char mode, sure enough - there are characters I would not expect (much less want) to be in there.
Collation of my database collation value shows as: SQL_Latin1_General_CP1_CI_AS
How would I go about eliminating any/all non-visible characters?
can try this, will remove any characters that are not printable.
CREATE FUNCTION [dbo].[RemoveNonPrintableChars]
(
#p_string varchar(max)
)
RETURNS varchar(max)
AS
BEGIN
declare #l_pos int = 1
declare #l_str varchar(max) = ''
while (#l_pos <= len(#p_string))
begin
if (ascii(substring(#p_string,#l_pos,1)) >=32)
begin
set #l_str=#l_str+substring(#p_string,#l_pos,1)
end
set #l_pos = #l_pos+1
end
return #l_str
END
declare
#l_str varchar(max) = 'andrew'--select char(7)
select dbo.[RemoveNonPrintableChars] (#l_str)
set #l_str = 'andrew'+char(7)-- add NP character
select dbo.[RemoveNonPrintableChars] (#l_str)
If by chance you can't use a UDF.
You may notice that I don't just strip the control characters here, I replace them with a space so not to concatenate strings.
Declare #YourTable table (SomeField varchar(50))
Insert Into #YourTable values
('Michael'+char(13)+char(10)+'LastName')
Select A.*
,B.Value
From #YourTable A
Cross Apply (
Select Value = replace(replace((
Select ''+C
From (
Select N,C=case when ASCII(Substring(A.SomeField,N ,1))>31 then Substring(A.SomeField,N ,1) else '{--space--}' end
From ( Select Top (Len(A.SomeField)) N=Row_Number() Over (Order By Number) From master..spt_values ) N
) C Order by N
For XML Path('') ) ,'{--space--}',' '),' ',' ')
) B
Returns
SomeField Value
Michael Michael LastName
LastName
EDIT
However, If you do want a UDF consider the following non-linear approach
CREATE FUNCTION [dbo].[udf-Str-Strip-Control](#S varchar(max))
Returns varchar(max)
Begin
;with cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
cte2(C) As (Select Top (32) Char(Row_Number() over (Order By (Select NULL))-1) From cte1 a,cte1 b)
Select #S = Replace(#S,C,' ')
From cte2
Return LTrim(RTrim(Replace(Replace(#S,' ',' '),' ',' ')))
End
--Select [dbo].[udf-Str-Strip-Control]('Michael'+char(13)+char(10)+'LastName') --Returns: Michael LastName
I like John's answers better, and would probably modify them if you were looking to control whether or not to include certain control characters. This is the function I used in the past to clean up some strings.
create function dbo.fnCleanVarchar (
#StringParameter varchar(max)
, #CleanStyle tinyint = 1
) returns varchar(max) as
begin;
if #StringParameter is null
return null;
if #CleanStyle > 3 set #CleanStyle = 1;
declare #StringReturn varchar(max);
declare #StringLength int;
declare #CharacterCode int;
declare #CharacterCodePosition int;
set #StringReturn = '';
set #StringLength = len(#StringParameter);
set #CharacterCodePosition = 1;
while #CharacterCodePosition <= #StringLength
begin
set #CharacterCode = ascii(substring(#stringParameter , #CharacterCodePosition , 1))
-- Removes Unprintable Characters 0-8,12,14-31
-- If Style = 1, Remove Unprintable Characters except Tab (9), New Line (10), Carraige Return (13)
-- If Style = 2, Remove Unprintable Characters except character 9 (Tab)
-- If Style = 3, Remove Unprintable Characters and character 9 (Tab)
set #StringReturn = #StringReturn + case
when #CharacterCode >31
then char(#CharacterCode)
when #Style = 3
then ''
when #Style = 2 and #CharacterCode = 9
then char(9)
when #Style = 1 and #CharacterCode in ( 9 , 10 , 13 )
then char(#CharacterCode)
else ''
end;
set #CharacterCodePosition = #CharacterCodePosition + 1
end;
if len(#StringReturn) = 0
return null;
return #StringReturn
end;
Checking for non-visible fields is directly related to find non-visible characters, so consider these two notes:
Note 1: SQL Server will auto-trimming spaces in clauses so N' ' = N'' is true, and any continues strings of empty characters;
Empty characters are a character that is equal to N''.
Note 2: There are 65536 Unicode characters, you can view them with a query like this:
WITH CTE(i, c) AS (
SELECT 0, NCHAR(0) COLLATE SQL_Latin1_General_CP1_CI_AS --I add COLLATE to express your collation but I think it is optional
UNION ALL
SELECT i+1, NCHAR(i+1) COLLATE SQL_Latin1_General_CP1_CI_AS
FROM CTE
WHERE i < 65535
)
SELECT *
FROM CTE
OPTION ( MaxRecursion 0 );
Some of those are not visible and empty like NCHAR(0), NCHAR(12288), ...,
Some of those are not visible and not empty like NCHAR(1), ...,
Some of those are visible and empty like NCHAR(502), ... !!!!.
So if your field is a nvarchar string, you will have a big problem to filter not visible characters, and for varchar strings you have a problem but more little than that.
Side note: You can use COALESCE(myString, '') != '' instead of yours ;).
SUMMARY :
For a little pin don't create a hammer machine!.
When this behaviors are not so important for you and your project don't try to change or handle or create your own equal string function ;).
A sample function to check if a string is visible(returns 1) or not(returns 0) can be like this:
CREATE FUNCTION IsVisible ( #string varchar(max) )
RETURNS bit
AS
BEGIN
DECLARE #pString varchar(max) = #string;
WITH InvisibleChars AS (
SELECT c COLLATE SQL_Latin1_General_CP1_CI_AS AS c
FROM (VALUES (CHAR(0)), (CHAR(1)), (CHAR(9)), (CHAR(10)),
(CHAR(11)), (CHAR(12)), (CHAR(13)), (CHAR(28)),
(CHAR(29)), (CHAR(30)), (CHAR(31)), (CHAR(32)),
(CHAR(160)) -- Above characters are non-visibles
) t(c)
)
SELECT #pString = REPLACE(#pString, c, '')
FROM InvisibleChars;
RETURN CASE WHEN #pString = '' THEN 0 ELSE 1 END;
END
GO
I came with a problem of sorting using ORDER BY. I found a lot of similar questions, but no answer fits my needs. The task is:
I have column [LABEL] which contains strings, and i want to get an order like this:
label
'1'
'2'
'11R'
'11T9'
'11T10'
'RT_5'
'RT_6'
'RT_10'
'RT_10b'
'RT_10dyn'
and so on...
instead of:
'1'
'11R'
'11T10'
'11T9'
'2S'
'RT_10'
'RT_10b'
'RT_10dyn'
'RT_5'
'RT_6'
the label columb might be like any combination of characters.
The problem is to find numbers in names, and if it is possible to sort by those numbers, then by other charaters...
After a few hours here is the solution:
I created a function to change the labels in specific way:
Each NUMBER in the input #in is replaced by the same number
writen in #digits chars WITH leadings zeros.
For example:
#digit = 4, #in = 'aa300bb' return = '_aa0300bb_'.
#digit = 5, #in = 'aa300bb' return = '_aa00300bb_'.
#digit = 3, #in = 'a2c4e5' return = '_a002c004e005_'.
And here is the function:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fnMixSort]')
AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fnMixSort]
GO
CREATE FUNCTION [dbo].[fnMixSort] (
#in NVARCHAR(250),
#digits int
) RETURNS NVARCHAR(1000) AS
BEGIN
DECLARE
#starts int,
#i int, -- position where next NUMBER starts
#j int, -- position where next NUMBER ends
#temp nvarchar(1000)
set #starts = 1
set #in = '_' + #in + '_' -- extended LABEL: protection from EMPTY input
while (1=1)
begin
select #temp = substring(#in, #starts, len(#in))
-- #i #j - start/end position of first number
SELECT #i = COALESCE( PATINDEX('%[0-9]%',#temp ), 0)
SELECT #j = COALESCE( PATINDEX('%[0-9][^0-9]%',#temp ), 0)
if #i = 0 break -- no more NUMBERs in the LABEL
-- now we PUT at posiotion=#i+#start-1 specific numbers of '0'
select #in = STUFF(#in, #i + #starts - 1, 0, REPLICATE('0', #digits-#j+#i-1))
select #starts = #starts + #i + #digits - 1
end
-- -------- return ---------
RETURN #in
END
GO
lets create some table to check the function:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[aaaa_test]')
AND type in (N'U'))
DROP TABLE [dbo].[aaaa_test]
GO
CREATE TABLE [dbo].[aaaa_test](
Label [varchar](255) NULL
)
INSERT INTO [dbo].[aaaa_test] ([Label])
VALUES ('bb'),('aa12'),(''),('30'),('10rt'),
('12ru'),('1rt'),('9rt'),('aa8'),('aa10'),('aa'),
('12rz'),('12rt'),('9rt5'),('9_rt_10_23'),('9_rt_10_5'),('9rt12'),
('12rz34'),('12rz3'),('12rz35c'),('12rz105b'),('12rt'),('9rt5'),('9rt10'),('9rt12')
select
[label]
,dbo.fnMixSort(Label,5) as [fnMixSort_returns]
from [dbo].[aaaa_test]
order by dbo.fnMixSort(Label,5)
And the result
label fnMixSort_returns
----------------------------------
1rt _00001rt_
9_rt_10_5 _00009_rt_00010_00005_
9_rt_10_23 _00009_rt_00010_00023_
9rt _00009rt_
9rt5 _00009rt00005_
9rt5 _00009rt00005_
9rt10 _00009rt00010_
9rt12 _00009rt00012_
9rt12 _00009rt00012_
10rt _00010rt_
12rt _00012rt_
12rt _00012rt_
12ru _00012ru_
12rz _00012rz_
12rz3 _00012rz00003_
12rz34 _00012rz00034_
12rz35c _00012rz00035c_
12rz105b _00012rz00105b_
30 _00030_
aa _aa_
aa8 _aa00008_
aa10 _aa00010_
aa12 _aa00012_
bb _bb_
it was my first time to post here...
hope it will help someone oneday..
You can substr [LABEL] column into different columns and then order by those columns. As null is sorted first you don't need to do anything extra for values with less character.
How ever you can also follow this thread here.
Here in this solution the logic is :-
If ID is numeric, add 21 '0's in front of the ID value and get the last 20 characters.
If ID is not numeric, add 21 ‘’s at the end of the ID value and get the first 20 characters.
Or this is a better solution for you query Sort Alphanumeric value
Let us see if it helps.
ANOTHER SOLUTION: different exchanged_label:
/** ==========================================================
FUNCTION DESCRIPTION
-------------------------------------------------------------
Function for special sorting - natural-mix sorting.
Order by : number in word are treated as number, not as a
characters only.
So 'a2' is before 'a10' and '9R' is before '10R' ...
-------------------------------------------------------------
Function puts special prefix before each number.
If number has 1 digit -> with prefix is 0A
If number has 2 digits -> with prefix is 0B
... ... ...
If number has 16 digits -> with prefix is 0P
If number has 17 digits -> with prefix is 0PA
If number has 18 digits -> with prefix is 0PB
... ... ...
If number has 32 digits -> with prefix is 0PP
If number has 33 digits -> with prefix is 0PPA
... and so on...
For example:
aa123bb9 -> aa0C123bb0A9
**/
CODE
CREATE FUNCTION [dbo].[fnMixSort] ( #in NVARCHAR(1000) ) RETURNS NVARCHAR(1000) AS
BEGIN
DECLARE
#starts int,
#i int, -- position where next NUMBER starts
#j int, -- position where next NUMBER ends
#temp nvarchar(1000)
set #starts = 1
set #in = '_' + #in + '_' -- extended LABEL: protection from EMPTY input
while (1=1)
begin
select #temp = substring(#in, #starts, len(#in))
SELECT #i = COALESCE( PATINDEX('%[0-9]%',#temp ), 0)
if #i = 0 break -- no more NUMBERs in the LABEL
SELECT #j = COALESCE( PATINDEX('%[0-9][^0-9]%',#temp ), 0)
select #temp = '0' -- numbers->must still be numbers: before letters
while (#j >= #i + 16)
begin
select #j = #j - 16
select #temp = #temp + 'P'
end
select #temp = #temp + CHAR(#j - #i + 65) -- char(65) is 'A'
select #in = STUFF(#in, #i + #starts - 1, 0, #temp)
select #starts = #starts + LEN(#temp) + (LEN(#temp)-2)*16 + #j
end -- while
RETURN #in
END
GO
results:
1rt _0A1rt_
9_rt_10_5 _0A9_rt_0B10_0A5_
9_rt_10_23 _0A9_rt_0B10_0B23_
9rt _0A9rt_
9rt5 _0A9rt0A5_
9rt5 _0A9rt0A5_
9rt10 _0A9rt0B10_
9rt12 _0A9rt0B12_
9rt12 _0A9rt0B12_
10rt _0B10rt_
12rt _0B12rt_
12rt _0B12rt_
12ru _0B12ru_
12rz _0B12rz_
12rz3 _0B12rz0A3_
12rz34 _0B12rz0B34_
12rz105b _0B12rz0C105b_
30 _0B30_
9234567890123456123456789012345rz38c _0PO9234567890123456123456789012345rz0B38c_
12345678901234561234567890123456rz35c _0PP12345678901234561234567890123456rz0B35c_
123456789012345612345678901234561rz36c _0PPA123456789012345612345678901234561rz0B36c_
aa _aa_
aa0A _aa0A0A_
aa0b _aa0A0b_
aa8 _aa0A8_
aa10 _aa0B10_
aa12 _aa0B12_
bb _bb_
Same approach as pi.314 but rewrite for PostgreSQL:
CREATE OR REPLACE FUNCTION fnNumberAwareSort(value varchar, digits integer)
RETURNS varchar
AS '
DECLARE
numbers VARCHAR[];
texts VARCHAR[];
BEGIN
value = CONCAT(''_'', value, ''_'');
SELECT ARRAY(SELECT res[1] FROM regexp_matches(value, ''\d+'', ''g'') AS res) INTO numbers;
texts = regexp_split_to_array(value, ''\d+'');
FOR i IN 1..array_upper(texts,1) LOOP
numbers[i] = lpad(numbers[i], digits, ''0'');
END LOOP;
value = texts[1];
FOR i IN 2..array_upper(texts,1) LOOP
value = value || numbers[i-1] || texts[i];
END LOOP;
RETURN value;
END;
' LANGUAGE plpgsql;
If you wanted to generate a pseudorandom alphanumeric string using T-SQL, how would you do it? How would you exclude characters like dollar signs, dashes, and slashes from it?
Using a guid
SELECT #randomString = CONVERT(varchar(255), NEWID())
very short ...
Similar to the first example, but with more flexibility:
-- min_length = 8, max_length = 12
SET #Length = RAND() * 5 + 8
-- SET #Length = RAND() * (max_length - min_length + 1) + min_length
-- define allowable character explicitly - easy to read this way an easy to
-- omit easily confused chars like l (ell) and 1 (one) or 0 (zero) and O (oh)
SET #CharPool =
'abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789.,-_!$##%^&*'
SET #PoolLength = Len(#CharPool)
SET #LoopCount = 0
SET #RandomString = ''
WHILE (#LoopCount < #Length) BEGIN
SELECT #RandomString = #RandomString +
SUBSTRING(#Charpool, CONVERT(int, RAND() * #PoolLength) + 1, 1)
SELECT #LoopCount = #LoopCount + 1
END
I forgot to mention one of the other features that makes this more flexible. By repeating blocks of characters in #CharPool, you can increase the weighting on certain characters so that they are more likely to be chosen.
When generating random data, specially for test, it is very useful to make the data random, but reproducible. The secret is to use explicit seeds for the random function, so that when the test is run again with the same seed, it produces again exactly the same strings. Here is a simplified example of a function that generates object names in a reproducible manner:
alter procedure usp_generateIdentifier
#minLen int = 1
, #maxLen int = 256
, #seed int output
, #string varchar(8000) output
as
begin
set nocount on;
declare #length int;
declare #alpha varchar(8000)
, #digit varchar(8000)
, #specials varchar(8000)
, #first varchar(8000)
declare #step bigint = rand(#seed) * 2147483647;
select #alpha = 'qwertyuiopasdfghjklzxcvbnm'
, #digit = '1234567890'
, #specials = '_## '
select #first = #alpha + '_#';
set #seed = (rand((#seed+#step)%2147483647)*2147483647);
select #length = #minLen + rand(#seed) * (#maxLen-#minLen)
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
declare #dice int;
select #dice = rand(#seed) * len(#first),
#seed = (rand((#seed+#step)%2147483647)*2147483647);
select #string = substring(#first, #dice, 1);
while 0 < #length
begin
select #dice = rand(#seed) * 100
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
if (#dice < 10) -- 10% special chars
begin
select #dice = rand(#seed) * len(#specials)+1
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
select #string = #string + substring(#specials, #dice, 1);
end
else if (#dice < 10+10) -- 10% digits
begin
select #dice = rand(#seed) * len(#digit)+1
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
select #string = #string + substring(#digit, #dice, 1);
end
else -- rest 80% alpha
begin
declare #preseed int = #seed;
select #dice = rand(#seed) * len(#alpha)+1
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
select #string = #string + substring(#alpha, #dice, 1);
end
select #length = #length - 1;
end
end
go
When running the tests the caller generates a random seed it associates with the test run (saves it in the results table), then passed along the seed, similar to this:
declare #seed int;
declare #string varchar(256);
select #seed = 1234; -- saved start seed
exec usp_generateIdentifier
#seed = #seed output
, #string = #string output;
print #string;
exec usp_generateIdentifier
#seed = #seed output
, #string = #string output;
print #string;
exec usp_generateIdentifier
#seed = #seed output
, #string = #string output;
print #string;
Update 2016-02-17: See the comments bellow, the original procedure had an issue in the way it advanced the random seed. I updated the code, and also fixed the mentioned off-by-one issue.
Use the following code to return a short string:
SELECT SUBSTRING(CONVERT(varchar(40), NEWID()),0,9)
If you are running SQL Server 2008 or greater, you could use the new cryptographic function crypt_gen_random() and then use base64 encoding to make it a string. This will work for up to 8000 characters.
declare #BinaryData varbinary(max)
, #CharacterData varchar(max)
, #Length int = 2048
set #BinaryData=crypt_gen_random (#Length)
set #CharacterData=cast('' as xml).value('xs:base64Binary(sql:variable("#BinaryData"))', 'varchar(max)')
print #CharacterData
I'm not expert in T-SQL, but the simpliest way I've already used it's like that:
select char((rand()*25 + 65))+char((rand()*25 + 65))
This generates two char (A-Z, in ascii 65-90).
select left(NEWID(),5)
This will return the 5 left most characters of the guid string
Example run
------------
11C89
9DB02
For one random letter, you can use:
select substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ',
(abs(checksum(newid())) % 26)+1, 1)
An important difference between using newid() versus rand() is that if you return multiple rows, newid() is calculated separately for each row, while rand() is calculated once for the whole query.
Here is a random alpha numeric generator
print left(replace(newid(),'-',''),#length) //--#length is the length of random Num.
There are a lot of good answers but so far none of them allow a customizable character pool and work as a default value for a column. I wanted to be able to do something like this:
alter table MY_TABLE add MY_COLUMN char(20) not null
default dbo.GenerateToken(crypt_gen_random(20))
So I came up with this. Beware of the hard-coded number 32 if you modify it.
-- Converts a varbinary of length N into a varchar of length N.
-- Recommend passing in the result of CRYPT_GEN_RANDOM(N).
create function GenerateToken(#randomBytes varbinary(max))
returns varchar(max) as begin
-- Limit to 32 chars to get an even distribution (because 32 divides 256) with easy math.
declare #allowedChars char(32);
set #allowedChars = 'abcdefghijklmnopqrstuvwxyz012345';
declare #oneByte tinyint;
declare #oneChar char(1);
declare #index int;
declare #token varchar(max);
set #index = 0;
set #token = '';
while #index < datalength(#randomBytes)
begin
-- Get next byte, use it to index into #allowedChars, and append to #token.
-- Note: substring is 1-based.
set #index = #index + 1;
select #oneByte = convert(tinyint, substring(#randomBytes, #index, 1));
select #oneChar = substring(#allowedChars, 1 + (#oneByte % 32), 1); -- 32 is the number of #allowedChars
select #token = #token + #oneChar;
end
return #token;
end
This worked for me: I needed to generate just three random alphanumeric characters for an ID, but it could work for any length up to 15 or so.
declare #DesiredLength as int = 3;
select substring(replace(newID(),'-',''),cast(RAND()*(31-#DesiredLength) as int),#DesiredLength);
Another simple solution with the complete alphabet:
SELECT LEFT(REPLACE(REPLACE((SELECT CRYPT_GEN_RANDOM(16) FOR XML PATH(''), BINARY BASE64),'+',''),'/',''),16);
Replace the two 16's with the desired length.
Sample result:
pzyMATe3jJwN1XkB
I realize that this is an old question with many fine answers. However when I found this I also found a more recent article on TechNet by Saeid Hasani
T-SQL: How to Generate Random Passwords
While the solution focuses on passwords it applies to the general case. Saeid works through various considerations to arrive at a solution. It is very instructive.
A script containing all the code blocks form the article is separately available via the TechNet Gallery, but I would definitely start at the article.
For SQL Server 2016 and later, here is a really simple and relatively efficient expression to generate cryptographically random strings of a given byte length:
--Generates 36 bytes (48 characters) of base64 encoded random data
select r from OpenJson((select Crypt_Gen_Random(36) r for json path))
with (r varchar(max))
Note that the byte length is not the same as the encoded size; use the following from this article to convert:
Bytes = 3 * (LengthInCharacters / 4) - Padding
I came across this blog post first, then came up with the following stored procedure for this that I'm using on a current project (sorry for the weird formatting):
CREATE PROCEDURE [dbo].[SpGenerateRandomString]
#sLength tinyint = 10,
#randomString varchar(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #counter tinyint
DECLARE #nextChar char(1)
SET #counter = 1
SET #randomString = ”
WHILE #counter <= #sLength
BEGIN
SELECT #nextChar = CHAR(48 + CONVERT(INT, (122-48+1)*RAND()))
IF ASCII(#nextChar) not in (58,59,60,61,62,63,64,91,92,93,94,95,96)
BEGIN
SELECT #randomString = #randomString + #nextChar
SET #counter = #counter + 1
END
END
END
I did this in SQL 2000 by creating a table that had characters I wanted to use, creating a view that selects characters from that table ordering by newid(), and then selecting the top 1 character from that view.
CREATE VIEW dbo.vwCodeCharRandom
AS
SELECT TOP 100 PERCENT
CodeChar
FROM dbo.tblCharacter
ORDER BY
NEWID()
...
SELECT TOP 1 CodeChar FROM dbo.vwCodeCharRandom
Then you can simply pull characters from the view and concatenate them as needed.
EDIT: Inspired by Stephan's response...
select top 1 RandomChar from tblRandomCharacters order by newid()
No need for a view (in fact I'm not sure why I did that - the code's from several years back). You can still specify the characters you want to use in the table.
I use this procedure that I developed simply stipluate the charaters you want to be able to display in the input variables, you can define the length too.
Hope this formats well, I am new to stack overflow.
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND object_id = OBJECT_ID(N'GenerateARandomString'))
DROP PROCEDURE GenerateARandomString
GO
CREATE PROCEDURE GenerateARandomString
(
#DESIREDLENGTH INTEGER = 100,
#NUMBERS VARCHAR(50)
= '0123456789',
#ALPHABET VARCHAR(100)
='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
#SPECIALS VARCHAR(50)
= '_=+-$£%^&*()"!#~#:',
#RANDOMSTRING VARCHAR(8000) OUT
)
AS
BEGIN
-- Author David Riley
-- Version 1.0
-- You could alter to one big string .e.e numebrs , alpha special etc
-- added for more felxibility in case I want to extend i.e put logic in for 3 numbers, 2 pecials 3 numbers etc
-- for now just randomly pick one of them
DECLARE #SWAP VARCHAR(8000); -- Will be used as a tempoary buffer
DECLARE #SELECTOR INTEGER = 0;
DECLARE #CURRENTLENGHT INTEGER = 0;
WHILE #CURRENTLENGHT < #DESIREDLENGTH
BEGIN
-- Do we want a number, special character or Alphabet Randonly decide?
SET #SELECTOR = CAST(ABS(CHECKSUM(NEWID())) % 3 AS INTEGER); -- Always three 1 number , 2 alphaBET , 3 special;
IF #SELECTOR = 0
BEGIN
SET #SELECTOR = 3
END;
-- SET SWAP VARIABLE AS DESIRED
SELECT #SWAP = CASE WHEN #SELECTOR = 1 THEN #NUMBERS WHEN #SELECTOR = 2 THEN #ALPHABET ELSE #SPECIALS END;
-- MAKE THE SELECTION
SET #SELECTOR = CAST(ABS(CHECKSUM(NEWID())) % LEN(#SWAP) AS INTEGER);
IF #SELECTOR = 0
BEGIN
SET #SELECTOR = LEN(#SWAP)
END;
SET #RANDOMSTRING = ISNULL(#RANDOMSTRING,'') + SUBSTRING(#SWAP,#SELECTOR,1);
SET #CURRENTLENGHT = LEN(#RANDOMSTRING);
END;
END;
GO
DECLARE #RANDOMSTRING VARCHAR(8000)
EXEC GenerateARandomString #RANDOMSTRING = #RANDOMSTRING OUT
SELECT #RANDOMSTRING
Sometimes we need a lot of random things: love, kindness, vacation, etc.
I have collected a few random generators over the years, and these are from Pinal Dave and a stackoverflow answer I found once. Refs below.
--Adapted from Pinal Dave; http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/
SELECT
ABS( CAST( NEWID() AS BINARY( 6)) %1000) + 1 AS RandomInt
, CAST( (ABS( CAST( NEWID() AS BINARY( 6)) %1000) + 1)/7.0123 AS NUMERIC( 15,4)) AS RandomNumeric
, DATEADD( DAY, -1*(ABS( CAST( NEWID() AS BINARY( 6)) %1000) + 1), GETDATE()) AS RandomDate
--This line from http://stackoverflow.com/questions/15038311/sql-password-generator-8-characters-upper-and-lower-and-include-a-number
, CAST((ABS(CHECKSUM(NEWID()))%10) AS VARCHAR(1)) + CHAR(ASCII('a')+(ABS(CHECKSUM(NEWID()))%25)) + CHAR(ASCII('A')+(ABS(CHECKSUM(NEWID()))%25)) + LEFT(NEWID(),5) AS RandomChar
, ABS(CHECKSUM(NEWID()))%50000+1 AS RandomID
This will produce a string 96 characters in length, from the Base64 range (uppers, lowers, numbers, + and /). Adding 3 "NEWID()" will increase the length by 32, with no Base64 padding (=).
SELECT
CAST(
CONVERT(NVARCHAR(MAX),
CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
,2)
AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
If you are applying this to a set, make sure to introduce something from that set so that the NEWID() is recomputed, otherwise you'll get the same value each time:
SELECT
U.UserName
, LEFT(PseudoRandom.StringValue, LEN(U.Pwd)) AS FauxPwd
FROM Users U
CROSS APPLY (
SELECT
CAST(
CONVERT(NVARCHAR(MAX),
CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), U.UserID) -- Causes a recomute of all NEWID() calls
,2)
AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
) PseudoRandom
CREATE OR ALTER PROC USP_GENERATE_RANDOM_CHARACTER ( #NO_OF_CHARS INT, #RANDOM_CHAR VARCHAR(40) OUTPUT)
AS
BEGIN
SELECT #RANDOM_CHAR = SUBSTRING (REPLACE(CONVERT(VARCHAR(40), NEWID()), '-',''), 1, #NO_OF_CHARS)
END
/*
USAGE:
DECLARE #OUT VARCHAR(40)
EXEC USP_GENERATE_RANDOM_CHARACTER 13,#RANDOM_CHAR = #OUT OUTPUT
SELECT #OUT
*/
Small modification of Remus Rusanu code -thanks for sharing
This generate a random string and can be used without the seed value
declare #minLen int = 1, #maxLen int = 612, #string varchar(8000);
declare #length int;
declare #seed INT
declare #alpha varchar(8000)
, #digit varchar(8000)
, #specials varchar(8000)
, #first varchar(8000)
declare #step bigint = rand() * 2147483647;
select #alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
, #digit = '1234567890'
, #specials = '_##-/\ '
select #first = #alpha + '_#';
set #seed = (rand(#step)*2147483647);
select #length = #minLen + rand(#seed) * (#maxLen-#minLen)
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
declare #dice int;
select #dice = rand(#seed) * len(#first),
#seed = (rand((#seed+#step)%2147483647)*2147483647);
select #string = substring(#first, #dice, 1);
while 0 < #length
begin
select #dice = rand(#seed) * 100
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
if (#dice < 10) -- 10% special chars
begin
select #dice = rand(#seed) * len(#specials)+1
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
select #string = #string + substring(#specials, #dice, 1);
end
else if (#dice < 10+10) -- 10% digits
begin
select #dice = rand(#seed) * len(#digit)+1
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
select #string = #string + substring(#digit, #dice, 1);
end
else -- rest 80% alpha
begin
declare #preseed int = #seed;
select #dice = rand(#seed) * len(#alpha)+1
, #seed = (rand((#seed+#step)%2147483647)*2147483647);
select #string = #string + substring(#alpha, #dice, 1);
end
select #length = #length - 1
end
SELECT #string
Heres something based on New Id.
with list as
(
select 1 as id,newid() as val
union all
select id + 1,NEWID()
from list
where id + 1 < 10
)
select ID,val from list
option (maxrecursion 0)
I thought I'd share, or give back to the community ...
It's ASCII based, and the solution is not perfect but it works quite well.
Enjoy,
Goran B.
/*
-- predictable masking of ascii chars within a given decimal range
-- purpose:
-- i needed an alternative to hashing alg. or uniqueidentifier functions
-- because i wanted to be able to revert to original char set if possible ("if", the operative word)
-- notes: wrap below in a scalar function if desired (i.e. recommended)
-- by goran biljetina (2014-02-25)
*/
declare
#length int
,#position int
,#maskedString varchar(500)
,#inpString varchar(500)
,#offsetAsciiUp1 smallint
,#offsetAsciiDown1 smallint
,#ipOffset smallint
,#asciiHiBound smallint
,#asciiLoBound smallint
set #ipOffset=null
set #offsetAsciiUp1=1
set #offsetAsciiDown1=-1
set #asciiHiBound=126 --> up to and NOT including
set #asciiLoBound=31 --> up from and NOT including
SET #inpString = '{"config":"some string value", "boolAttr": true}'
SET #length = LEN(#inpString)
SET #position = 1
SET #maskedString = ''
--> MASK:
---------
WHILE (#position < #length+1) BEGIN
SELECT #maskedString = #maskedString +
ISNULL(
CASE
WHEN ASCII(SUBSTRING(#inpString,#position,1))>#asciiLoBound AND ASCII(SUBSTRING(#inpString,#position,1))<#asciiHiBound
THEN
CHAR(ASCII(SUBSTRING(#inpString,#position,1))+
(case when #ipOffset is null then
case when ASCII(SUBSTRING(#inpString,#position,1))%2=0 then #offsetAsciiUp1 else #offsetAsciiDown1 end
else #ipOffset end))
WHEN ASCII(SUBSTRING(#inpString,#position,1))<=#asciiLoBound
THEN '('+CONVERT(varchar,ASCII(SUBSTRING(#Inpstring,#position,1))+1000)+')' --> wrap for decode
WHEN ASCII(SUBSTRING(#inpString,#position,1))>=#asciiHiBound
THEN '('+CONVERT(varchar,ASCII(SUBSTRING(#inpString,#position,1))+1000)+')' --> wrap for decode
END
,'')
SELECT #position = #position + 1
END
select #MaskedString
SET #inpString = #maskedString
SET #length = LEN(#inpString)
SET #position = 1
SET #maskedString = ''
--> UNMASK (Limited to within ascii lo-hi bound):
-------------------------------------------------
WHILE (#position < #length+1) BEGIN
SELECT #maskedString = #maskedString +
ISNULL(
CASE
WHEN ASCII(SUBSTRING(#inpString,#position,1))>#asciiLoBound AND ASCII(SUBSTRING(#inpString,#position,1))<#asciiHiBound
THEN
CHAR(ASCII(SUBSTRING(#inpString,#position,1))+
(case when #ipOffset is null then
case when ASCII(SUBSTRING(#inpString,#position,1))%2=1 then #offsetAsciiDown1 else #offsetAsciiUp1 end
else #ipOffset*(-1) end))
ELSE ''
END
,'')
SELECT #position = #position + 1
END
select #maskedString
This uses rand with a seed like one of the other answers, but it is not necessary to provide a seed on every call. Providing it on the first call is sufficient.
This is my modified code.
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND object_id = OBJECT_ID(N'usp_generateIdentifier'))
DROP PROCEDURE usp_generateIdentifier
GO
create procedure usp_generateIdentifier
#minLen int = 1
, #maxLen int = 256
, #seed int output
, #string varchar(8000) output
as
begin
set nocount on;
declare #length int;
declare #alpha varchar(8000)
, #digit varchar(8000)
, #specials varchar(8000)
, #first varchar(8000)
select #alpha = 'qwertyuiopasdfghjklzxcvbnm'
, #digit = '1234567890'
, #specials = '_##$&'
select #first = #alpha + '_#';
-- Establish our rand seed and store a new seed for next time
set #seed = (rand(#seed)*2147483647);
select #length = #minLen + rand() * (#maxLen-#minLen);
--print #length
declare #dice int;
select #dice = rand() * len(#first);
select #string = substring(#first, #dice, 1);
while 0 < #length
begin
select #dice = rand() * 100;
if (#dice < 10) -- 10% special chars
begin
select #dice = rand() * len(#specials)+1;
select #string = #string + substring(#specials, #dice, 1);
end
else if (#dice < 10+10) -- 10% digits
begin
select #dice = rand() * len(#digit)+1;
select #string = #string + substring(#digit, #dice, 1);
end
else -- rest 80% alpha
begin
select #dice = rand() * len(#alpha)+1;
select #string = #string + substring(#alpha, #dice, 1);
end
select #length = #length - 1;
end
end
go
In SQL Server 2012+ we could concatenate the binaries of some (G)UIDs and then do a base64 conversion on the result.
SELECT
textLen.textLen
, left((
select CAST(newid() as varbinary(max)) + CAST(newid() as varbinary(max))
where textLen.textLen is not null /*force evaluation for each outer query row*/
FOR XML PATH(''), BINARY BASE64
),textLen.textLen) as randomText
FROM ( values (2),(4),(48) ) as textLen(textLen) --define lengths here
;
If you need longer strings (or you see = characters in the result) you need to add more + CAST(newid() as varbinary(max)) in the sub select.
Here's one I came up with today (because I didn't like any of the existing answers enough).
This one generates a temp table of random strings, is based off of newid(), but also supports a custom character set (so more than just 0-9 & A-F), custom length (up to 255, limit is hard-coded, but can be changed), and a custom number of random records.
Here's the source code (hopefully the comments help):
/**
* First, we're going to define the random parameters for this
* snippet. Changing these variables will alter the entire
* outcome of this script. Try not to break everything.
*
* #var {int} count The number of random values to generate.
* #var {int} length The length of each random value.
* #var {char(62)} charset The characters that may appear within a random value.
*/
-- Define the parameters
declare #count int = 10
declare #length int = 60
declare #charset char(62) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
/**
* We're going to define our random table to be twice the maximum
* length (255 * 2 = 510). It's twice because we will be using
* the newid() method, which produces hex guids. More later.
*/
-- Create the random table
declare #random table (
value nvarchar(510)
)
/**
* We'll use two characters from newid() to make one character in
* the random value. Each newid() provides us 32 hex characters,
* so we'll have to make multiple calls depending on length.
*/
-- Determine how many "newid()" calls we'll need per random value
declare #iterations int = ceiling(#length * 2 / 32.0)
/**
* Before we start making multiple calls to "newid", we need to
* start with an initial value. Since we know that we need at
* least one call, we will go ahead and satisfy the count.
*/
-- Iterate up to the count
declare #i int = 0 while #i < #count begin set #i = #i + 1
-- Insert a new set of 32 hex characters for each record, limiting to #length * 2
insert into #random
select substring(replace(newid(), '-', ''), 1, #length * 2)
end
-- Now fill the remaining the remaining length using a series of update clauses
set #i = 0 while #i < #iterations begin set #i = #i + 1
-- Append to the original value, limit #length * 2
update #random
set value = substring(value + replace(newid(), '-', ''), 1, #length * 2)
end
/**
* Now that we have our base random values, we can convert them
* into the final random values. We'll do this by taking two
* hex characters, and mapping then to one charset value.
*/
-- Convert the base random values to charset random values
set #i = 0 while #i < #length begin set #i = #i + 1
/**
* Explaining what's actually going on here is a bit complex. I'll
* do my best to break it down step by step. Hopefully you'll be
* able to follow along. If not, then wise up and come back.
*/
-- Perform the update
update #random
set value =
/**
* Everything we're doing here is in a loop. The #i variable marks
* what character of the final result we're assigning. We will
* start off by taking everything we've already done first.
*/
-- Take the part of the string up to the current index
substring(value, 1, #i - 1) +
/**
* Now we're going to convert the two hex values after the index,
* and convert them to a single charset value. We can do this
* with a bit of math and conversions, so function away!
*/
-- Replace the current two hex values with one charset value
substring(#charset, convert(int, convert(varbinary(1), substring(value, #i, 2), 2)) * (len(#charset) - 1) / 255 + 1, 1) +
-- (1) -------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^-----------------------------------------
-- (2) ---------------------------------^^^^^^^^^^^^^^^^^^^^^^11111111111111111111111^^^^-------------------------------------
-- (3) --------------------^^^^^^^^^^^^^2222222222222222222222222222222222222222222222222^------------------------------------
-- (4) --------------------333333333333333333333333333333333333333333333333333333333333333---^^^^^^^^^^^^^^^^^^^^^^^^^--------
-- (5) --------------------333333333333333333333333333333333333333333333333333333333333333^^^4444444444444444444444444--------
-- (6) --------------------5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555^^^^----
-- (7) ^^^^^^^^^^^^^^^^^^^^66666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666^^^^
/**
* (1) - Determine the two hex characters that we'll be converting (ex: 0F, AB, 3C, etc.)
* (2) - Convert those two hex characters to a a proper hexadecimal (ex: 0x0F, 0xAB, 0x3C, etc.)
* (3) - Convert the hexadecimals to integers (ex: 15, 171, 60)
* (4) - Determine the conversion ratio between the length of #charset and the range of hexadecimals (255)
* (5) - Multiply the integer from (3) with the conversion ratio from (4) to get a value between 0 and (len(#charset) - 1)
* (6) - Add 1 to the offset from (5) to get a value between 1 and len(#charset), since strings start at 1 in SQL
* (7) - Use the offset from (6) and grab a single character from #subset
*/
/**
* All that is left is to add in everything we have left to do.
* We will eventually process the entire string, but we will
* take things one step at a time. Round and round we go!
*/
-- Append everything we have left to do
substring(value, 2 + #i, len(value))
end
-- Select the results
select value
from #random
It's not a stored procedure, but it wouldn't be that hard to turn it into one. It's also not horrendously slow (it took me ~0.3 seconds to generate 1,000 results of length 60, which is more than I'll ever personally need), which was one of my initial concerns from all of the string mutation I'm doing.
The main takeaway here is that I'm not trying to create my own random number generator, and my character set isn't limited. I'm simply using the random generator that SQL has (I know there's rand(), but that's not great for table results). Hopefully this approach marries the two kinds of answers here, from overly simple (i.e. just newid()) and overly complex (i.e. custom random number algorithm).
It's also short (minus the comments), and easy to understand (at least for me), which is always a plus in my book.
However, this method cannot be seeded, so it's going to be truly random each time, and you won't be able to replicate the same set of data with any means of reliability. The OP didn't list that as a requirement, but I know that some people look for that sort of thing.
I know I'm late to the party here, but hopefully someone will find this useful.
Based on various helpful responses in this article I landed with a combination of a couple options I liked.
DECLARE #UserId BIGINT = 12345 -- a uniqueId in my system
SELECT LOWER(REPLACE(NEWID(),'-','')) + CONVERT(VARCHAR, #UserId)
Below are the way to Generate 4 Or 8 Characters Long Random Alphanumeric String in SQL
select LEFT(CONVERT(VARCHAR(36),NEWID()),4)+RIGHT(CONVERT(VARCHAR(36),NEWID()),4)
SELECT RIGHT(REPLACE(CONVERT(VARCHAR(36),NEWID()),'-',''),8)
So I liked a lot of the answers above, but I was looking for something that was a little more random in nature. I also wanted a way to explicitly call out excluded characters. Below is my solution using a view that calls the CRYPT_GEN_RANDOM to get a cryptographic random number. In my example, I only chose a random number that was 8 bytes. Please note, you can increase this size and also utilize the seed parameter of the function if you want. Here is the link to the documentation: https://learn.microsoft.com/en-us/sql/t-sql/functions/crypt-gen-random-transact-sql
CREATE VIEW [dbo].[VW_CRYPT_GEN_RANDOM_8]
AS
SELECT CRYPT_GEN_RANDOM(8) as [value];
The reason for creating the view is because CRYPT_GEN_RANDOM cannot be called directly from a function.
From there, I created a scalar function that accepts a length and a string parameter that can contain a comma delimited string of excluded characters.
CREATE FUNCTION [dbo].[fn_GenerateRandomString]
(
#length INT,
#excludedCharacters VARCHAR(200) --Comma delimited string of excluded characters
)
RETURNS VARCHAR(Max)
BEGIN
DECLARE #returnValue VARCHAR(Max) = ''
, #asciiValue INT
, #currentCharacter CHAR;
--Optional concept, you can add default excluded characters
SET #excludedCharacters = CONCAT(#excludedCharacters,',^,*,(,),-,_,=,+,[,{,],},\,|,;,:,'',",<,.,>,/,`,~');
--Table of excluded characters
DECLARE #excludedCharactersTable table([asciiValue] INT);
--Insert comma
INSERT INTO #excludedCharactersTable SELECT 44;
--Stores the ascii value of the excluded characters in the table
INSERT INTO #excludedCharactersTable
SELECT ASCII(TRIM(value))
FROM STRING_SPLIT(#excludedCharacters, ',')
WHERE LEN(TRIM(value)) = 1;
--Keep looping until the return string is filled
WHILE(LEN(#returnValue) < #length)
BEGIN
--Get a truly random integer values from 33-126
SET #asciiValue = (SELECT TOP 1 (ABS(CONVERT(INT, [value])) % 94) + 33 FROM [dbo].[VW_CRYPT_GEN_RANDOM_8]);
--If the random integer value is not in the excluded characters table then append to the return string
IF(NOT EXISTS(SELECT *
FROM #excludedCharactersTable
WHERE [asciiValue] = #asciiValue))
BEGIN
SET #returnValue = #returnValue + CHAR(#asciiValue);
END
END
RETURN(#returnValue);
END
Below is an example of the how to call the function.
SELECT [dbo].[fn_GenerateRandomString](8,'!,#,#,$,%,&,?');
May this will be an answer to create random lower & upper characters. It's using a while loop which can be controlled to generate the string with a specific length.
--random string generator
declare #maxLength int = 5; --max length
declare #bigstr varchar(10) --uppercase character
declare #smallstr varchar(10) --lower character
declare #i int = 1;
While #i <= #maxLength
begin
set #bigstr = concat(#bigstr, char((rand()*26 + 65)));
set #smallstr = concat(#smallstr, char((rand()*26 + 96)));
set #i = len(#bigstr)
end
--select query
select #bigstr, #smallstr