Rename files on disk with t-sql

后端 未结 3 1021
南笙
南笙 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:38

    SET NOCOUNT ON;
    
     CREATE TABLE #FileList
        (
         FileID INT IDENTITY(1, 1)
        ,Line VARCHAR(512)
        )  
    
     CREATE TABLE #temp
        (
         isFileThere BIT
        ,isDirectory BIT
        ,parentDirExists BIT
        )
    
     DECLARE @Command VARCHAR(1024)
     ,  @RowCount INT
     ,  @counter INT
     ,  @FileName VARCHAR(1024)
     ,  @FileExists BIT
     SET @Command = 'dir C:\MyFiles\  /A-D  /B'
    
     PRINT @Command
     INSERT #FileList
            EXEC master.dbo.xp_cmdshell @Command
    
     DELETE FROM #FileList
     WHERE  Line IS NULL
    
     SELECT @RowCount = COUNT(*)
     FROM   [#FileList]
    
     SET @counter = 1
    
     WHILE ( @counter <= @RowCount ) 
        BEGIN
            SELECT  @FileName = [Line]
            FROM    [#FileList]
            WHERE   [FileID] = @counter 
    
            SET @Command = 'C:\MyFiles\' + @FileName + ''
    
     PRINT @Command
    
            INSERT  [#temp]
                    EXEC master.dbo.xp_fileExist @Command
    
            SELECT  @FileExists = [isFileThere]
            FROM    [#temp] 
    
    
            IF @FileExists = 1
                AND CHARINDEX('''', @FileName) > 0 
                SET @Command = 'REN "C:\MyFiles\' + @FileName + '" "'
                    + REPLACE(@FileName, '''', '') + '"'
            ELSE 
                SET @Command = ''
    
            SET @counter = @counter + 1
    
            PRINT @Command
    
            IF LEN(@Command) > 0 
                EXEC master.dbo.xp_cmdshell @Command
    
        END 
    
     DROP TABLE #FileList
    
     DROP TABLE [#temp]
    

提交回复
热议问题