<cfwhat>

Thursday, July 05, 2012

List manipulation in SQL

Here are a three functions for list manipulation using SQL.

@RowData is the name of a column.
@SplitOn is the list delimiter (eg comma, period, space etc)

Get the first item:
ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

Get the last item:
right(@RowData, charindex('.', reverse(@RowData), 1) - 1)

Get the list without the first item:
Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))

These are the equivalent of ColdFusion's ListFirst(), ListLast() and ListRest() functions.

2 Comments:

  • Love it.

    But with the ListFirst():
    will it return empty string if you do not have delimiter

    with the second one:
    I think you meant ListRest() rather than ListLast()

    Peter Pham

    By Blogger Peter Pham, at 5:20 pm  

  • Yes I did mean ListRest. Thanks for pointing that out.

    By Blogger Richard, at 10:31 am  

Post a Comment

<< Home