I have a table that has these records on SQL Server
RepID iBegin iEnd RepText
1 10 17 This is a profile of ... Moreover Toyota has been ... such as Mazda also ...
1 38 44 This is a profile of ... Moreover Toyota has been ... such as Mazda also ...
1 77 82 This is a profile of ... Moreover Toyota has been ... such as Mazda also ...
2 21 24 ... flights to USA will be...weather temp is 73 degrees ...
2 82 82 ... flights to USA will be...weather temp is 73 degrees ...
this table has a text (HTML) and I need to highlight the text that is in between iBegin and iEnd by adding the <red>
before and after the highlighted text
I did that on the row level
SELECT RepID, RepText, SUBSTRING(RepText,0, iBegin) + '<red>' + SUBSTRING(RepText,iBegin, iEnd-iBegin + 1) + '<\red>' + SUBSTRING(RepText, iEnd, Len(RepText)-iEnd + 1)
FROM table
but could not do that with group by so all highlights show in a single record like this
RepID RepText
1 This is a <red>profile</red> of ... Moreover <red>Toyota</red> has been ... such as <red>Mazda</red> also ...
2 ... flights to <red>USA</red> will be...weather temp is <red>73</red> degrees ...
Any idea how to do that?
2条答案
按热度按时间yjghlzjz1#
Depending on your version of SQL Server and whether such string processing is best done in the database...
This handles each wrapped segment with the non-wrapped segment just before it (via
lag()
) in pairs. Each of those must then be concatenated in proper order along with the final segment at the end. This does assume no overlap in your offsets but that's pretty much a given anyway.https://dbfiddle.uk/n2beW4E0
f5emj3cl2#
I'm not sure if your
iBegin
andiEnd
are correct... Here's a way to do it with aUDF
andGROUP BY
:First the
UDF
Then the call would be
And if your data looks like this, you would get your expected output: