Generate Random String in SQL

There a better ways of generating random strings in your application using PHP, C#, Python or whatever OOP language you are using but if you need to do this at the database level then here’s a clever little trick using a view and an SQL function.

Basically you create a view that holds a part (or all) of a Unique Identifier. In this example, I hold 12 characters. The SQL function is then just used to query the view and present the random string.

IF OBJECT_ID('dbo.fn_randomString') IS NOT NULL
DROP FUNCTION dbo.fn_randomString;
GO
 
CREATE VIEW dbo.vwRandomString 
AS SELECT RIGHT(CONVERT(VARCHAR(255), NEWID()), 12) AS rand_str;
GO
 
CREATE FUNCTION dbo.fn_RandomString()
RETURNS VARCHAR(12)
AS
BEGIN
DECLARE @randomString VARCHAR(12);
 
SET @randomString = (SELECT rand_str FROM dbo.vwRandomString);
 
RETURN @randomString;
END