6

I'm using below query to split the names as shown below:

select value from STRING_SPLIT('Name1~Name2~Name3' , '~' );

How to get second name i.e, Name2, without using WHERE condition?

Note: Names can be dynamic

enter image description here

Santosh Jadi
  • 1,479
  • 6
  • 29
  • 55

3 Answers3

14

Try PARSENAME function

SELECT PARSENAME( REPLACE('Name1~Name2~Name3','~','.'),2)

output

Name2

PARSENAME Returns the specified part of an object name. The parts of an object that can be retrieved are the object name, owner name, database name, and server name.

Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
Chanukya
  • 5,833
  • 1
  • 22
  • 36
12

Instead of using STRING_SPLIT you can convert your string to XML and then use .value to retrieve the 2nd element:

SELECT CAST('<t>' + REPLACE('Name1~Name2~Name3' , '~','</t><t>') + '</t>' AS XML).value('/t[2]','varchar(50)')
Andrea
  • 11,801
  • 17
  • 65
  • 72
  • 1
    This is actually the correct answer. Parsename has some caveats allowing for wrong values seeping in. I didn't debug why this happened, but it was enough for me to conclude the fallacy. This, however, is perfect. – BNazaruk Dec 06 '22 at 23:07
3

Try below code:

SELECT TOP 1 T.* FROM 
(SELECT TOP 2 * FROM STRING_SPLIT('Name1~Name2~Name3' , '~' ) ORDER BY value ASC) AS T
ORDER BY value DESC;