简体   繁体   中英

Is there anyway to “compress” this SQL Query further?

I have wrote a SQL query which makes sure a filename is unique in a table. If the parameter being passed is NULL then this is assigned a random value before being checked.

Here is my code:

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

Is there anyway of compressing this onto less lines?

er... yes.

You can lose the BEGIN END too for a single statement for the WHILE. And add a semi-colon or 2: but these are only for clarity in this case.

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

Here is an alternative way of solving the above problem:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM