mssql生成唯一代码

时间:2013-06-13 07:15:52

标签: sql-server stored-procedures recursion

请帮助我,我将如何在我的存储过程中执行一些递归语句。 这就是我想要的

-- @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

提前致谢

1 个答案:

答案 0 :(得分:3)

@requestcode以NULL开头(除非已经分配),因此第一个WHILE条件检查始终为true,至少提供一次迭代

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