2013-06-13 43 views
1

請幫我在這,我怎麼會做我的存儲過程中的一些遞歸語句。 這裏就是我想提前mssql生成唯一的代碼

-- @requestcode will genereate some random string i have already the code below 

set @requestcode = (SELECT substring(@username,0,3)+'-'+SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9)) 

-- then i want to check if the string generated is existing to 'sampletable' 
select @requestcode from sampletable 

-- if it is existing back to the @requestcode query until it is not existing 

感謝

回答

3

@requestcode開始爲NULL(除非已分配),所以也先條件檢查始終是真的,至少給出一個迭代

WHILE @requestcode IS NULL OR 
     EXISTS (SELECT * FROM sampletable WHERE requestcode = @requestcode) 
BEGIN 
    SELECT @requestcode = substring(@username,0,3) + '-' + 
      SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9)); 
END