Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Using UDFs to avoid cursors

By Cade Bryant,

Let's say you have 2 tables: a Contacts table and a PhoneNumbers table (which stores all the phone numbers for each contact).  You are asked to write a query that returns each contact's name and a comma-delimited string of phone numbers for each contact, something like this:

FirstName    LastName   PhoneNumbers
---------    --------   --------------------------
John         Smith      111-222-3333, 444-555-6666

Many developers would attempt to do this with a cursor.  While a cursor could certainly be coded to do the job, there is actually a more efficient way of doing this that doesn't require cursors or temp tables.

You would write a UDF that grabs the phone numbers, and then execute the UDF within a SELECT statement, as the following code demonstrates:

Total article views: 992 | Views in the last 30 days: 1
Related Articles

Format Phone Number function

Function to format phone numbers entered as text.


Phone number formatting

Phone number formatting


Clean international Phone Numbers

Gotta clean up phone numbers as I load into SQL and it is a mess!


Random Phone numbers

Can anyone help me generate a statement that will update a table with random phone numbers with the ...





Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones