我需要帮助解析以下模式的string
以检查date
并结帐date
SQL
'CheckIn: Thursday, April 05, 2012
CheckOut: Saturday, April 07, 2012'
我试过
select
SUBSTRING([stringToParse], CHARINDEX('Checkin: ', [stringToParse])+9, charindex('<',stringToParse)) as checkin_date,
SUBSTRING([stringToParse], CHARINDEX('CheckOut: ', [stringToParse])+10, LEN([stringToParse])) as checkout_date from xyztable
适用于结帐日期,但当我使用类似的方法parse
签入时,它会返回
'Thursday, April 05, 2012
Chec'
我需要解析签到date
答案 0 :(得分:0)
在SQL Server中语法为
SUBSTRING ( expression ,start , length )
因此,您需要从长度中减去您在开始时输入的9个字符,以获得正确的结果。
答案 1 :(得分:0)
substring()的第三个参数是长度,而不是偏移量。试试这个:
select SUBSTRING([stringToParse], CHARINDEX('Checkin: ', [stringToParse])+9, charindex('< br/>',stringToParse)-11) as checkin_date,
SUBSTRING([stringToParse], CHARINDEX('CheckOut: ', [stringToParse])+10, LEN([stringToParse])) as checkout_date
from (select 'CheckIn: Thursday, April 05, 2012 < br/>CheckOut: Saturday, April 07, 2012' as stringtoparse
) t
答案 2 :(得分:0)
有时它帮助我使用len(字符串)而不是替换长度值,并在它自己的行上分解每个参数。
select
SUBSTRING
(
stringToParse, -- string
CharIndex('CheckIn: ', stringToParse) + LEN('CheckIn: '), -- Start
charindex('< br/>',stringToParse) - /*You want the position of the < br/> MINUS the position of the end of the CheckIn: */(CharIndex('CheckIn: ', stringToParse) + LEN('CheckIn: ')) -- # of characters
) as checkin_date
,
SUBSTRING
(
stringToParse,
CHARINDEX('CheckOut: ', stringToParse)+10,
LEN(stringToParse)
) as checkout_date