2011-02-24 44 views
0

我寫了一個SQL查詢,確保文件名在表中是唯一的。如果傳遞的參數是NULL,那麼在檢查之前這被分配一個隨機值。反正有沒有進一步「壓縮」這個SQL查詢?

這裏是我的代碼:

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

反正是有這個壓縮到更小的行?

+0

它,但具有到位不使這個SQL查詢自動發生的(?我不認爲),它會拋出一個我相信的約束錯誤? – Curt 2011-02-24 11:23:51

+0

你爲什麼需要這樣做? – 2011-02-24 11:41:59

回答

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, @[email protected]; WHILE (SELECT COUNT(*) FROM [eJournals] WHERE [FileName][email protected]) > 0 SELECT @FileNameCheck = @FileName + '-' + CAST(@i as nvarchar(3)), @[email protected]+1; SET @FileName = @FileNameCheck 
+0

太棒了!感謝@gbn這將使我對這段代碼的多次使用看起來不那麼凌亂,並教會了我關於在一行上循環的一點:D – Curt 2011-02-24 11:26:59

+0

@Curt如果你在多個地方使用它,你不應該真的使用用戶定義功能呢?或者每個副本的代碼都會有輕微的變化 – Seph 2012-06-05 13:20:00

+0

@Seph是的,它會改變,如果你看腳本,它會提到列名和表名。這隨每次使用腳本而改變。 – Curt 2012-06-06 08:45:49

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)