0

I have a column named Item(varchar(max)) in my SQL server it contains cell data as follow:

'1|2|3|4|5'

I want output as :

1
2
3
4
5

Is it possible to do so using SQL Server Management Studio.

Fabio
  • 23,183
  • 12
  • 55
  • 64

2 Answers2

0

Though I highly advise separating yourself from delimited values, if you have to use them, you can use the following method:

Create the Table Function:

CREATE FUNCTION dbo.splitStringByPipe
(@string nvarchar(500))
RETURNS TABLE 
AS
RETURN 
(
 SELECT  
     Split.a.value('.', 'VARCHAR(100)') AS String  
 FROM  (SELECT  
         CAST ('<M>' + REPLACE(@string, '|', '</M><M>') + '</M>' AS XML) AS String) AS A CROSS APPLY String.nodes ('/M') AS Split(a)     
)
GO

Execute the function:

SELECT * FROM dbo.splitStringByPipe('1|a|5|z|r')

Returns:

  | String
1 | 1
2 | a
3 | 5
4 | z
5 | r
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • Sir, i want count of '1' after receiving output as desired..Please Help – Utkarsh Agrawal Jan 04 '17 at 21:31
  • Please provide an example of the table you'll be selecting from, and your final desired output. Without knowing anything about your structure, I cannot elaborate on my answer any further. – Tyler Roper Jan 04 '17 at 21:37
0

FOR XML (SQL Server)

A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query.

More Detail for XML(SQL Server)

;WITH CTE1
AS
(
SELECT CAST(('<r><c>' + REPLACE(TestColumn, '|', '</c></r><r><c>') + '</c></r>' ) AS XML) XmlColumn
FROM tbl_Employee
),
TBL2
AS
(
SELECT  CAST(Col.query('./text()') AS VARCHAR(10))Result
FROM 
CTE1 CROSS APPLY 
XmlColumn.nodes('/r/c') As Tab(Col)
)
SELECT * FROM TBL2

Output :

 Result 
-  1 -
-  2 -
-  3 -
-  4 - 
-  5 -