Home > database >  How SQL randomly generated to specify the length of the string
How SQL randomly generated to specify the length of the string

Time:11-08

Ask god how to assign to the field randomly generated database length, the string
Field is the only can't repeat, best can specify is number + + capital letters lowercase letter combinations , or 24 upper and lower case letters, or all uppercase letters,

I want to use these strings to do content link URL, hope to know a great god, the knowledge of

For example, I randomly generated number
The update table set field=floor (1 + rand () * 108)



CodePudding user response:

Newid () can generate a random string, don't need you to pay attention to the other written,

 select newid () AS string, len (newid ()) AS stringLen 
/*
String stringLen
243 aae6e - A019-49 a4 - A41C - 5 eebdca7fe1c 36
*/

Select the left (newid (), 10) AS string length of 10
/*
7 cbf3cf9 -f
*/

CodePudding user response:

Is not well, I'm need batch to a field in database executes the how to write?

As is shown in

CodePudding user response:

Batch can also use the newid ()
 
The update tableName set column=newId ();

CodePudding user response:


IF OBJECT_ID (' v_NewID) IS NOT NULL DROP VIEW v_NewID
GO
The CREATE VIEW v_NewID AS SELECT NEWID () AS MacoID
GO

- generate random code
IF OBJECT_ID (' uf_RandCode) IS NOT NULL DROP FUNCTION uf_RandCode
GO
The CREATE FUNCTION uf_RandCode (@ nDigit Integer, @ UpperOrLower TinyInt) RETURNS nVarChar (Max) AS
The BEGIN
DECLARE @ maco_wang TABLE (ID nVarChar (1))
DECLARE @ maco_number Integer, @ number Integer, @ my_one nVarChar (Max), @ my_two nVarChar (Max)
The SET @ my_one=' '; The SET @ maco_number=0; The SET @ number=48;
WHILE (@ number & gt;=48 AND @ number & lt;=57) OR (@ number & gt;=65 AND @ number & lt;=90) OR (@ number & gt;=97 AND @ number & lt;
=122)The BEGIN
INSERT INTO @ maco_wang SELECT CHAR (@ number)
The SET @ number=@ number + 1
IF (@ number=58) SET @ number=65
IF (@ number=91) SET @ number=97
END
WHILE @ maco_number & lt; @ nDigit
The BEGIN
SELECT the FROM @ @ my_two=id maco_wang ORDER BY (SELECT MacoID FROM v_NewID)
The SET @ my_one=@ my_two + @ my_one
The SET @ maco_number=@ maco_number + 1
END
IF @ UpperOrLower=1 - lowercase
The SET @ my_one=LOWER (@ my_one)
ELSE IF @ UpperOrLower capital
=2 -The SET @ my_one=UPPER (@ my_one)
RETURN the @ my_one
END
GO
  • Related