日期:2014-05-17  浏览次数:20473 次

截取guid..........
我现在要写一个存储过程,输出一个值(输出的是是newid的前8位)
不过要和一个表里的code进行对比,如果存在就继续截取,不存在就直接输出。
改怎么写啊???
if OBJECT_ID('code','u') is not null
drop table code
go
create table code
(
    ID int identity(1,1) not null,
    Code varchar(8) not null,
    VGUID uniqueidentifier default(newid()) not null
)
insert into code(Code) values (LEFT(NEWID(),8))

------解决方案--------------------
大致如下:
declare @id uniqueidentifier = newid()
      , @idtemp uniqueidentifier

set @idtemp = (select newid())

while ((select LEFT(@idtemp,8)) <> (select LEFT(@id,8)))
begin
set @idtemp = (select newid())
end
select @id, @idtemp
提示,这个循环几乎不太可能结束。
------解决方案--------------------
create procedure test
as
declare @str char(8)
declare @a int
set @a=1
  select @str=SUBSTRING( NEWID(),0,9)
  
  while(@a=1)
  begin
   if exists (select * from code where code=@str)
   begin
     select @str=SUBSTRING( NEWID(),0,9)
   end
   else
   begin
     set @a=2
   end
  end 
  
  select @str
------解决方案--------------------
DECLARE @a VARCHAR(8)

A:
SELECT @a=left(NEWID(),8)
IF EXISTS(SELECT 1 FROM Code WHERE code=@a)
GOTO A
INSERT Code(Code) SELECT @a
 
------解决方案--------------------
我觉得 #3 即可。
------解决方案--------------------
declare @guid varchar(8)
set @guid=left(newid(),8)
while 1=1
begin
if exists
(
select 1 from guidTest where guid=@guid
)
begin
print 'exists:'+@guid
set @guid=left(newid(),8)
end
else 
begin
print 'notExists:'+@guid
insert into guidTest values(@guid)
break
end
end