在TSQL中查找编号最大的重复文件名

时间:2016-07-15 16:00:15

标签: tsql

我的网站上有一个工具可以上传文件,当文件名存储在数据库中时。然后将文件传输到单独的服务器。

所以当我上传时,我需要检查数据库中是否有任何同名文件。如果有,我需要在括号内附加一个数字到文件末尾(就像Windows对重复文件一样)。

但是,我很难找到要追加的号码。

这是我暂时使用的TSQL程序:

ALTER PROCEDURE [dbo].[sp_getDuplicateCloudEntry]
(
@file_name nvarchar(75),
@file_ext nvarchar(6)
   )
   AS

DECLARE @iHighestDuplicate as integer = 0

--Extracts the number inside of the parentheses of the file name if there's a match
--If there's a duplicate but it's not numbered, don't return anything and the procedure will return a 0 later to let you know there is one duplicate but it is unnumbered
SELECT TOP 1 @iHighestDuplicate =  SUBSTRING(file_name,LEN(@file_name) + 2, len([file_name]) - len(@file_name) - len(@file_ext) -2) FROM tblCloud WHERE file_name LIKE @file_name + '%' + @file_ext
AND (len([file_name]) - len(@file_name) - len(@file_ext) -2) > 0
ORDER BY CAST(SUBSTRING(file_name,LEN(@file_name) + 2, len([file_name]) - len(@file_name) - len(@file_ext) -2) as int) Desc

IF @iHighestDuplicate = 0 BEGIN
    IF EXISTS (SELECT * FROM tblCloud WHERE file_name LIKE @file_name + '%' + @file_ext) BEGIN
    --there is a duplicate so return 0
    --.vb portion will add 1 to it and append it
        SELECT 0 as HighestDuplicate
    END 
    --if no return then do nothing
END ELSE BEGIN
    --there is more than one duplicate and we will grab the highest number appended
    Select @iHighestDuplicate as HighestDuplicate
END

数据库中的file_name包含扩展名(例如“Test.pdf”),传入的@file_ext包含句点(例如“.pdf”)。

这个问题是,有时它会在文件名上找到匹配项,因为它实际上并不完全重复,因为还有其他字符。例如,如果数据库中存在名为“Testing.pdf”的文件,则会在输入“Test.pdf”上找到匹配项。然后它将尝试从“Testing.pdf”中提取数字并得到错误。

我有更好的方法来做这个,或者解决我的问题与文件名匹配吗?

0 个答案:

没有答案