Batch renaming of files in SQL Server

Source: Internet
Author: User
-- 1. Create a UDF: truncates a string from the last specific character.
Create   Function Fn_getlastcharindex ( @ Chars   Varchar ( 1000 ), @ Char   Varchar ( 10 ))
Returns   Varchar ( 1000 )
Begin
Declare   @ I   Int
Set   @ I = Charindex ( @ Char , @ Chars )
While ( @ I > 0 )
Begin
Set   @ Chars = Substring ( @ Chars , @ I + 1 , Len ( @ Chars ))
Set   @ I = Charindex ( @ Char , @ Chars )
End

Return   @ Chars
End

-- 2. Get the file name list
If   Exists ( Select   *   From Tempdb .. sysobjects Where ID = Object_id ( ' Tempdb .. # temp ' ))
Drop   Table # Temp
Create   Table # Temp (Filenames Varchar ( 1000 ))
Insert   Into # Temp (Filenames)
Exec Master .. xp_mongoshell ' Dir F: \ dunk expert-full-color edition of the National Competition '

-- 3. Rename
Declare   @ Filename   Varchar ( 1000 ),
@ Newfilename   Varchar ( 1000 ),
@ S   Varchar ( 1000 )
Declare Cur_1 Cursor   For
Select DBO. fn_getlastcharindex (filenames, '   ' ) Filename From # Temp   Where   Right (Filenames, 4 ) In ( ' . Jpg ' ) And Filenames Like   ' % Slamdunk % '   Order   By   1
Open Cur_1
Fetch Cur_1 Into   @ Filename
While ( @ Fetch_status = 0 )
Begin
Set   @ Newfilename   =   Replace ( @ Filename , DBO. fn_getlastcharindex ( @ Filename , ' - ' ), Right ( ' 00 ' + DBO. fn_getlastcharindex ( @ Filename , ' - ' ), 7 ))
Set   @ S = ' Ren F: \ dunk experts-all-color edition of national competitions \ '   +   @ Filename   +   '   '   +   @ Newfilename
Exec Master .. xp_mongoshell @ S , No_output
Fetch Cur_1 Into   @ Filename
End
Deallocate Cur_1

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.