Rename files on disk with t-sql

后端 未结 3 1013
南笙
南笙 2021-01-16 04:15

I am using T-SQL

I have a few excel files located here: C:\\MyFiles\\

I want to remove all the apostrophes in the file names in that directory.<

3条回答
  •  臣服心动
    2021-01-16 04:41

    Try this it will work for you

    1) Create a sp as mentioned below

    CREATE PROCEDURE dbo.ListPathsXML
    @FileSpec VARCHAR(2000),
    @order VARCHAR (80) = '/O-D',--sort by date time oldest first
    @xmlFileList XML OUTPUT
    
    AS
    DECLARE @myfiles TABLE (MyID INT IDENTITY(1,1) PRIMARY KEY, FullPath VARCHAR(2000))
    DECLARE @CommandLine VARCHAR(4000)
    IF @order IS NOT NULL -- abort if the order is silly
       BEGIN
       SELECT @CommandLine =LEFT('dir "' + @FileSpec + '" /A-D /B /S '+@order,4000)
       INSERT INTO @MyFiles (FullPath)
           EXECUTE xp_cmdshell @CommandLine
       DELETE FROM @MyFiles WHERE fullpath IS NULL
           OR fullpath = 'File Not Found'
       END
    SET @xmlFileList = (SELECT fullpath FROM @MyFiles
                             FOR
                              XML PATH('thefile'),
                                  ROOT('thefiles'),
                                  TYPE)
    

    2) and then give a name of directory where you want to replace the name of files

    DECLARE @LotsOfText NVARCHAR(MAX),
           @ii INT,
           @iiMax INT,
           @File VARCHAR(2000),
           @Command NVARCHAR(4000)
    DECLARE @files TABLE (MyID INT IDENTITY(1,1) PRIMARY KEY, [Path] VARCHAR(2000))
    
    DECLARE @FileList XML
    EXECUTE ListPathsXML 'D:\QAconfig\',
        DEFAULT , @XMLFileList = @FileList OUTPUT
    
    INSERT INTO @files(path)
       SELECT   x.thefile.value('fullpath[1]', 'varchar(2000)') AS [path]
            FROM    @FileList.nodes('//thefiles/thefile') AS x ( thefile )
    --don't look at the current errorlog!
    SELECT @ii=1, @iiMax=MAX(MyID) FROM @Files
    WHILE @ii<=@iiMax
       BEGIN
       SELECT @File= [path] FROM @files WHERE MyID=@ii
       print @File
       SELECT @command='EXEC master..xp_cmdshell' + '''MOVE '+ Replace(@FILE,'''','''''') + ' ' +REPLACE(@FILE,'''','') +''''
       print @command
       EXECUTE sp_ExecuteSQL @command--, N'@lotsOfText nvarchar(max) output ',@lotsoftext output 
       SELECT @ii=@ii+1
       END
    

提交回复
热议问题