Click here to Skip to main content
11,802,762 members (70,944 online)
Rate this: bad
Please Sign up or sign in to vote.
There is a text filed in a table called as description. I would like to extract two date fields from this string when there is an occurrence of '~' character using sql server 2005 stored procedure. Help me out in this case.

Example: string: '长期租金;10/1/2012 ~ 10/31/2012'. At occurrence of ~ operator I would like to have from-date: 20121001 and to-date: 20121031.
Posted 21-Oct-12 23:40pm
Edited 22-Oct-12 7:04am
Maciej Los202.3K
djj55 at 22-Oct-12 11:39am
Is the data you are looking for always dates? Or of a given size?
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

The easiest way is to use regular expressions. As SQL server does not support regular expressions by default, you have to extend it using .net integrated user function. It is really not complicated. See these two articles:[^], Regular Expressions in MS SQL Server 2005/2008[^].
If this task has to be done regularly, I suggest you implement two functions based on one of the above, that extracts first of last dates directly to sql date.
Maciej Los at 22-Oct-12 13:21pm
Great answer, +5!
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Use CHARINDEX[^] function to find ~ and then LEFT[^] or RIGHT[^] or SUBSTRING[^] function to return the part of string.

For example:
DECLARE @inputstring NVARCHAR(100)
DECLARE @fromdate NVARCHAR(10)
SET @inputstring = '长期租金;10/01/2012 ~ 10/31/2012'
SET @pos = CHARINDEX('~', @inputstring)
IF @pos >0
        SET @fromdate = SUBSTRING(@inputstring,@pos-11,10)
        SET @todate = SUBSTRING(@inputstring,@pos+1,10)
        SELECT @fromdate as [from-date], @todate as [to-date]
ELSE --@pos =0
    PRINT 'There''s no matches!'
damodara naidu betha at 24-Oct-12 3:18am
Maciej Los at 24-Oct-12 13:48pm
Thank you ;)
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

Hi ..,

try this batch

DECLARE @String VARCHAR(200) = '长期租金;10/1/2012 ~ 10/31/2012'
SET @String = SUBSTRING(@String,CHARINDEX(';',@String,0)+1,LEN(@String))
SELECT SUBSTRING(@String,0,CHARINDEX('~',@String,0)) [From-Date], 
SUBSTRING(@String,CHARINDEX('~',@String,0)+1,LEN(@String)) [To-Date]

Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 KrunalRohit 366
1 OriginalGriff 365
2 F-ES Sitecore 295
3 CPallini 270
4 Sergey Alexandrovich Kryukov 239
0 OriginalGriff 2,950
1 Maciej Los 1,910
2 KrunalRohit 1,862
3 CPallini 1,695
4 Richard MacCutchan 1,157

Advertise | Privacy | Mobile
Web03 | 2.8.151002.1 | Last Updated 24 Oct 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100