我有一个包含文件路径的表,如下所示:
--------------------
|Files |
--------------------
|path nvarchar(500)|
--------------------
我想将它拆分为两个表,一个包含唯一目录,另一个包含文件名:
---------------------------
|Files |
---------------------------
|filename nvarchar(255)|
|directoryId int |
---------------------------
---------------------------
|Directories |
---------------------------
|id int |
|path nvarchar(255)|
---------------------------
因此,例如,如果条目最初是“C:/folder/file.jpg”,我想在“C:/ folder /”的目录中输入一个条目,并且“文件”中的条目将更新为“文件”。 jpg“用于目录中新条目的文件名和目录ID。
(如果你在这一点上想知道,我需要这样做的原因是因为我需要在目录级别跟踪一些信息。)
在T SQL脚本中有一个好方法吗?
答案 0 :(得分:0)
试试这个:
declare @filename varchar(500)
set @filename = 'C:/Folder/file.jpg'
select right(@filename, charindex('/',reverse(@filename))-1)
select left(@filename, len(@filename) - charindex('/',reverse(@filename))+1)
这将是整个转换:
insert into Directories ([path])
select distinct
left([path], len([path]) - charindex('/',reverse([path]))+1) as [path]
from files
select
d.id,
right(f.[path], charindex('/',reverse(f.[path]))-1)
from files f
inner join directories d
on left(f.[path], len(f.[path]) - charindex('/',reverse(f.[path]))+1) = d.[path]
我不确定表的真实名称,因为您的架构中有两个文件表。
答案 1 :(得分:0)
DECLARE @FULL VARCHAR(50)
DECLARE @PATH VARCHAR(50)
DECLARE @FILE VARCHAR(50)
DECLARE @directoryId INT
DECLARE curs CURSOR FAST_FORWARD FOR
SELECT path FROM FILES_1
OPEN curs
FETCH NEXT FROM curs
INTO @FULL
WHILE @@FETCH_STATUS = 0
BEGIN
SET @FILE = right(@FULL, charindex('/',reverse(@FULL))-1)
SET @PATH = left(@FULL, len(@FULL) - charindex('/',reverse(@FULL))+1)
SET @directoryId = SELECT ID from Directories WHERE path = @PATH
BEGIN TRANSACTION
IF @directoryId IS NULL
BEGIN
INSERT INTO Directories VALUES (@PATH)
SET @directoryId = @@IDENTITY
END
INSERT INTO Files VALUES ( @FILE,@directoryId)
IF @@ERROR <> 0 ROLLBACK
COMMIT TRANSACTION
END
CLOSE curs
DEALLOCATE curs
更改为光标!