反正还有“压缩”这个SQL查询吗?

时间:2011-02-24 11:17:56

标签: sql sql-server-2005 tsql compression

我编写了一个SQL查询,确保文件名在表中是唯一的。如果传递的参数是NULL,那么在检查之前会为其分配一个随机值。

这是我的代码:

SET @FileName=REPLACE(ISNULL(@FileName, dbo.fn_String_GenerateRandom(NEWID(), 10)), ' ', '-')
DECLARE @i int,@FileNameCheck nvarchar(200); SELECT @i=2, @FileNameCheck=@FileName
WHILE (SELECT COUNT(*) FROM [eJournals] WHERE [FileName]=@FileNameCheck) > 0
BEGIN
    SELECT @FileNameCheck = @FileName + '-' + CAST(@i as nvarchar(3)), @i=@i+1
END
SET @FileName = @FileNameCheck

无论如何将它压缩到更少的线上?

2 个答案:

答案 0 :(得分:1)

呃......是的。

对于WHILE的单个语句,您也可能丢失BEGIN END。 并添加一个分号或2:但这些只是为了清晰起见。

SET @FileName=REPLACE(ISNULL(@FileName, dbo.fn_String_GenerateRandom(NEWID(), 10)), ' ', '-'); DECLARE @i int,@FileNameCheck nvarchar(200); SELECT @i=2, @FileNameCheck=@FileName; WHILE (SELECT COUNT(*) FROM [eJournals] WHERE [FileName]=@FileNameCheck) > 0 SELECT @FileNameCheck = @FileName + '-' + CAST(@i as nvarchar(3)), @i=@i+1; SET @FileName = @FileNameCheck

答案 1 :(得分:0)

以下是解决上述问题的另一种方法:

drop table Filenames
create table Filenames (fname varchar(200) not null)
insert into Filenames values ('hello.txt')
insert into Filenames values ('hello.txt0')
insert into Filenames values ('hello.txt1')
declare @fileName varchar(200) = 'hello.txt'

declare @realFileName varchar(200) = 
    (select top 1 f.fname from
         (select 0 as rownum, @filename as fname union
          select 
              row_number() over (order by fname) as rownum, 
              @filename + cast(row_number() over (order by fname) as varchar) as fname
          from Filenames) as f
     where f.fname not in (select fname from Filenames)
     order by f.rownum)