Click here to Skip to main content
13,551,001 members
Rate this:
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
Updated 22-Oct-12 7:04am
djj55 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 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 24-Oct-12 3:18am
Maciej Los 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
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04-2016 | 2.8.180515.1 | Last Updated 24 Oct 2012
Copyright © CodeProject, 1999-2018
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