How to generate alphanumeric tokens in SQL Server?
I am looking to generate soem alpha numeric开发者_如何学编程 tokens. Is there a function that can do to generate set length tokens?
You can do this and then take a substring of it of whatever length you need:
select replace(newid(), '-', '')
E.g., for eight characters:
select substring(replace(newid(), '-', ''), 1, 8)
I have done this by combining a unique id from the table with a random number:
update [table]
set token = cast([id] as varchar(10)) + cast(cast(round((rand() * 500000000.0), 0) as int) as varchar(10))
Adjust the varchar sizes and the multiplication factor to get the toekn size you need. If you need a precise size, make the resulting string a little too long and use substring to set the length.
This is not crytographically strong, but it works for me in most cases. Using the id field from the table guarantees that the token is unique, and the random number makes it difficult to guess.
Another possible solution (for SQL Server, i think NEWID() is not available in other DBMS but use another similar function):
SELECT CONVERT(VARCHAR(10), RIGHT(NEWID(), 5))
The NEWID() function returns a Alpha numeric ID generated by SQL Server which you can use in the way you need.
Works well for me.
精彩评论