Some time we need to split a long comma separated String in Stored procedure e.g. Sybase or SQL Server stored procedures. Its quite common to pass comma delimited or delimiter separated String as input parameter to Stored procedure and than later split comma separated String into multiple values inside stored proc. This is not just case of input parameter but you can also have comma separated string in any table data. Unfortunately there is no split() function in Sybase or SQL Server 2005 or 2008 which can directly split string based on delimiter just like in Java string split method. Fortunately Sybase Adaptive Server and Microsoft SQL server has functions like CHARINDEX and PATINDEX which can be used to split comma separated String. This is next on our SQL tutorials after seeing SQL query to find duplicate records in table and How to find 2nd and Nth maximum salary in SQL.
Sybase CHARINDEX Example to Split String
Here is code example of How to split string in Sybase adaptive server using CHARINDEX function. This can be used in any stored procedure to split any comma delimited String. In this example we have used CHARINDEX, LEFT and STUFF function to split comma delimited String into multiple values.
SET @string = 'abc,xyx,def'
declare @pos numeric(20)
declare @piece varchar(50)
SET @pos = charindex(',' , @string)
while @pos <> 0
begin
SET @piece = LEFT(@string, @pos-1)
print @piece
SET @string = stuff(@string, 1, @pos, NULL)
SET @pos = charindex(',' , @string)
end
print @string --this is required to print last string
Output:
abc
xyx
def
How to split string in Sybase using PATINDEX
SET @string = 'abc,xyx,def'
declare @pos numeric(20)
declare @piece varchar(50)
SET @pos = patindex('%,%' , @string)
while @pos <> 0
begin
SET @piece = LEFT(@string, @pos-1)
print @piece
SET @string = stuff(@string, 1, @pos, NULL)
SET @pos = charindex(',' , @string)
end
print @string --this is required to print last string
Output:
abc
xyx
def
Difference between correlated and noncorrelated subquery in SQL
When to use truncate vs delete in SQL
10 SELECT command examples in SQL
How to create table by copying schema from another table in SQL
How to join three tables in single SQL query
No comments:
Post a Comment