问题
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
.
回答1:
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.
回答2:
SELECT SUBSTRING(REPLACE(CONVERT(varchar, NEWID()), '-', ''), 1, 10)
来源:https://stackoverflow.com/questions/30144180/default-random-10-character-string-value-for-sql-server-column