Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Updated 22-Oct-12 7:04am
v2
Comments
Corporal Agarn 22-Oct-12 11:39am    
Is the data you are looking for always dates? Or of a given size?

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: http://msdn.microsoft.com/en-us/magazine/cc163473.aspx[^], 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.
 
Share this answer
 
Comments
Maciej Los 22-Oct-12 13:21pm    
Great answer, +5!
Use CHARINDEX[^] function to find ~ and then LEFT[^] or RIGHT[^] or SUBSTRING[^] function to return the part of string.

For example:
SQL
DECLARE @inputstring NVARCHAR(100)
DECLARE @pos INT
DECLARE @fromdate NVARCHAR(10)
DECLARE @todate NVARCHAR(10)

SET @inputstring = '长期租金;10/01/2012 ~ 10/31/2012'
SET @pos = CHARINDEX('~', @inputstring)

IF @pos >0
    BEGIN
        SET @fromdate = SUBSTRING(@inputstring,@pos-11,10)
        SET @todate = SUBSTRING(@inputstring,@pos+1,10)
        SELECT @fromdate as [from-date], @todate as [to-date]
    END
ELSE --@pos =0
    PRINT 'There''s no matches!'
 
Share this answer
 
v2
Comments
damodara naidu betha 24-Oct-12 3:18am    
5+
Maciej Los 24-Oct-12 13:48pm    
Thank you ;)
Hi ..,

try this batch

SQL
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
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900