[英]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. 我写了一个SQL查询,以确保文件名在表中是唯一的。 If the parameter being passed is
NULL
then this is assigned a random value before being checked. 如果传递的参数为
NULL
则在检查之前会为其分配一个随机值。
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. 对于WHILE的单个语句,您也可能会丢失BEGIN END。 And add a semi-colon or 2: but these are only for clarity in this case.
并添加一个分号或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
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.