How to Convert comma separated string as a sql table column
Example:- we need to convert the string "1212,23423,234,234234,254" as a-
Id |
1212 |
23423 |
234 |
234234 |
254 |
First Create a custom function in sql server database under Function -
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fnSplitter](@IDs Varchar(1000))
RETURNS @Tbl_IDs TABLE (ID Varchar(1000)) As
Begin
-- Append comma
Set @IDs = @IDs + ','
-- Indexes to keep the position of searching
Declare @Pos Int
Declare @Piece varchar(100)
if right(rtrim( @IDs),1) <> ','
-- Start from first character
Set @IDs = @IDs + ','
Set @Pos = patindex('%,%' , @IDs)
while @Pos <> 0
begin
Set @Piece = Left( @IDs, @Pos - 1)
Insert @Tbl_Ids Select Cast(@Piece as Varchar(500))
-- Go to next non comma character
Set @IDs = stuff( @IDs, 1, @Pos, '')
-- Search from the next character
Set @Pos = patindex('%,%' , @IDs)
end
RETURN
end
----------------------------------
Then execute the following query in sql server database, then you get above desire output-
select id from fnsplitter ('1212,23423,234,234234,234')
Comments
Post a Comment