2012-03-03 69 views

回答

3

該解決方案有點冗長,但工作原理很容易適應各種需求。下面是一些示例輸出:

aapx0k k4fdbb vzbl5x 
8vr1bs gbix1q g5kctv 
he6e50 m9j0m0 2vz53l 
yw72hs hgbo5h 3oen9v 
6t4q75 337670 5sf3h4 
yqr35s xoh4hh tc0wtf 
w7trkj lnnpdk zk2ln1 
1gt7qr l6m72n ja5kvm 
kg6f9y 6t3b7a ujfr0i 
2jatgo 0yv8rv wvbjfa 

請注意,您需要創建一個視圖來包裝這是不允許一個UDF內使用RAND的。所以這個解決方案需要兩個db對象,一個視圖和一個udf。

CREATE VIEW ViewRandInt AS (SELECT RAND() * 36 as RandInt) 
GO 

CREATE FUNCTION GetRandomBase36Id 
(
    @charCount AS INT 
) 
RETURNS VARCHAR(50) AS BEGIN 

    DECLARE @characters CHAR(36), 
      @result VARCHAR(MAX), 
      @counter INT, 
      @randNum INT 

    SELECT @characters = 'abcdefghijklmnopqrstuvwxyz', 
      @result = '', 
      @counter = 0; 


    WHILE @counter < @charCount 
    BEGIN 
     SELECT @randNum = RandInt FROM ViewRandInt 
     SET @result = @result + SUBSTRING(@characters, @randNum+1, 1) 
     SET @counter = @counter + 1 
    END 

    RETURN @result; 

END 

-- Test: 
SELECT dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6) 
+0

@Kumar:我想你可能已經接受了答案,然後我在原始答案中發佈了一個錯誤修復。請獲取最新的代碼示例。 (原始代碼被關閉了一個字符,當「z」是所選的隨機字符時,最終的ID沒有包含它。) – 2012-03-03 06:26:12