[英]String processing during table creation and inserting from another table
I have a table that contains file paths, like so: 我有一个包含文件路径的表,如下所示:
--------------------
|Files |
--------------------
|path nvarchar(500)|
--------------------
I want to split it into two tables, one containing unique directories and one containing filenames: 我想将其分为两个表,一个包含唯一目录,另一个包含文件名:
---------------------------
|Files |
---------------------------
|filename nvarchar(255)|
|directoryId int |
---------------------------
---------------------------
|Directories |
---------------------------
|id int |
|path nvarchar(255)|
---------------------------
So for example if an entry originally was "C:/folder/file.jpg", I want an entry in Directories for "C:/folder/", and the entry in Files would be updated to have "file.jpg" for the filename and the directory id of the new entry in Directories. 因此,例如,如果一个条目最初是“ C:/folder/file.jpg”,我希望在目录中输入一个“ C:/ folder /”,并且“文件”中的条目将被更新为“ file.jpg”目录中新条目的文件名和目录ID。
(In case you're wondering at this point, the reason I need to do this is because I need to keep track of some information at the directory level.) (如果您此时想知道,我之所以需要这样做是因为我需要在目录级别跟踪某些信息。)
Is there a good way to do this in a T SQL script? 有没有在T SQL脚本中执行此操作的好方法?
try this: 尝试这个:
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)
This will be the whole conversion: 这将是整个转换:
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]
I was not sure the real names of the tables because you have two Files tables in your schema. 我不确定表的真实名称,因为您的架构中有两个“文件”表。
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
Changed to a cursor! 更改为光标!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.