Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Sorting a cursor by substring

Author  Topic 

cornall
Posting Yak Master

148 Posts

Posted - 2007-11-01 : 12:27:27
Hi,

I get a list of files from an FTP server using a dir command and store the results in a cursor so I can process each file individualy.

The dir command returns the files in alphabetic order e.g.

a_01112007_100001.txt
b_01112007_090001.txt
c_01112007_080001.txt

I want to sort the files by the date e.g.

c_01112007_080001.txt
b_01112007_090001.txt
a_01112007_100001.txt

Can I do this easily in my cursor?

Cheers D


cornall
Posting Yak Master

148 Posts

Posted - 2007-11-01 : 12:53:20
Note the a,b and c will not always be 1 char long!

The files come from a 3rd party so can't change the file namaing convention!
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2007-11-01 : 13:44:27
I'm anti-cursor so I would use a WHILE loop, but that is up to you. Here is some sampe code that may help you:
-- Set up
DECLARE @File TABLE(FileName VARCHAR(50))

INSERT @File
SELECT 'a_01112007_100001.txt'
UNION ALL SELECT 'b_01112007_090001.txt'
UNION ALL SELECT 'c_01112007_080001.txt'

-- This could be used to load the cursor, but this is a VARCHAR sort not a date sort
SELECT RIGHT(PARSENAME(FileName, 2), LEN(PARSENAME(FileName, 2)) - (CHARINDEX('_', PARSENAME(FileName, 2))))
FROM @File
ORDER BY RIGHT(PARSENAME(FileName, 2), LEN(PARSENAME(FileName, 2)) - (CHARINDEX('_', PARSENAME(FileName, 2))))

-- This is how you could convert the file name to an acutal DATETIME for proper ordering
SELECT CAST(REPLACE(STUFF(STUFF(STUFF(STUFF(RIGHT(PARSENAME(FileName, 2), LEN(PARSENAME(FileName, 2)) - (CHARINDEX('_', PARSENAME(FileName, 2)))), 3, 0, '-'), 6, 0, '-'), 14, 0, ':'), 17, 0, ':'), '_', ' ') AS DATETIME)
FROM @File
Go to Top of Page
   

- Advertisement -