Using CharIndex, Len and Substring to locate certain information from a column

拈花ヽ惹草 提交于 2019-12-11 05:37:53

问题


Here's what I am trying to do, but failing miserably:

I am trying to retrieve address from a column that is 12000+ characters long. Lucky for me, I can locate the address line1 through XML tag:

<PermanentAddress> <AddressLine><![CDATA[1234 1st street]]></AddressLine> <City>

Here's what I have done so far:

select 
substring(PC.css_record, CHARINDEX('<AddressLine>', PC.css_record)+ 21, CHARINDEX('</AddressLine>', PC.css_record))
from 
table1

I tried squeezing length function in there too to calculate the length end of my substring function, but that just gave me an error (may be because I am new to SQL and still learning and used it wrong).

Also, there are multiple tags, but I am only concerned with the first one.

It would be very awesome if someone could help me out!

Thanks!


回答1:


Try this :

declare @xml xml = 
'<PermanentAddress> 
<AddressLine><![CDATA[1234 1st street]]>
</AddressLine> 
<City>test</City>
</PermanentAddress>'  

select @xml.value('(/PermanentAddress/AddressLine)[1]', 'nvarchar(100)')



回答2:


You found the beginning: CHARINDEX('<AddressLine>', PC.css_record) + 21
and the end: CHARINDEX('</AddressLine>', PC.css_record) - 3,
now you just need to compute the length by subtracting the beginning from the end: CHARINDEX('</AddressLine>', PC.css_record) - CHARINDEX('<AddressLine>', PC.css_record) - 24

select 
    substring(PC.css_record,
              CHARINDEX('<AddressLine>', PC.css_record) + 21,
              CHARINDEX('</AddressLine>', PC.css_record)
                  - CHARINDEX('<AddressLine>', PC.css_record) - 24)
from 
PC


来源:https://stackoverflow.com/questions/16784117/using-charindex-len-and-substring-to-locate-certain-information-from-a-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!