Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default random 10 character string value for SQL Server column

I have a column rndm in my table [guests]. Now, for the field Default value or Binding for the table, whenever a new row is inserted I want to automatically insert a 10-character random string into this column as the default value.

This random string may not contain special characters, only characters from a-zA-Z0-9. What is the best approach to achieve this?

To be clear: I don't want to generate this random string in my .NET code, I want it to be generated within SQL Server. And I want to paste this string generation directly into the field Default value or Binding for the table, so not a separate SQL statement. So for example like it works when pasting getdate() into the field Default value or Binding.

enter image description here

like image 868
Adam Avatar asked May 09 '15 19:05

Adam


2 Answers

Expanding on what Deigo Garbar has already suggested.

If you want to use the expression as the default value in your table you would need to put this expression in a function.

But the problem is a UDF function will not allow you to use NEWID() function in it, it will complain about cannot use non-deterministic function in UDF bla bla....

A way around will be to create a view first which simply calls this expression then use that view inside your function and then use that function as Default value for your table.

View

CREATE VIEW dbo.vw_Function_Base
AS
SELECT substring(replace(convert(varchar(100), NEWID()), '-', ''), 1, 10) AS Rand_Value

Function

CREATE FUNCTION dbo.fn_getRandom_Value()
RETURNS VARCHAR(10)
AS
BEGIN
  DECLARE @Rand_Value VARCHAR(10);
SELECT @Rand_Value = Rand_Value
FROM vw_Function_Base

  RETURN @Rand_Value;
END

Now you can use this function as default value in your table.

Test

CREATE TABLE SomeTest_Table
 ( ID        INT
 , RandValue VARCHAR(10) DEFAULT dbo.fn_getRandom_Value()
 )
GO

 INSERT INTO SomeTest_Table(ID)
 VALUES (1)
GO

 SELECT * FROM SomeTest_Table

Important Note

I am not convinced this Part of GUID value will always be unique, so be careful.

like image 101
M.Ali Avatar answered Sep 23 '22 18:09

M.Ali


SELECT SUBSTRING(REPLACE(CONVERT(varchar, NEWID()), '-', ''), 1, 10)
like image 20
diego garber Avatar answered Sep 25 '22 18:09

diego garber