Click here to monitor SSC
SQLServerCentral is supported by Redgate
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: 994 | 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 ...