A common need in SQL is the ability to iterate over a list as if it were an array. In SQL it is not possible to declare arrays, unlike other programming languages such as ColdFusion, ActionScript and Java. Fortunately, there is a way around this problem: use a User-Defined Functions (UDFs) to create a tabular version of the data. Arrays are, after all, essentially tabular data (at their simplest, one dimension level).
A User-Defined Function, is a function provided by the user of a program or environment. In SQL databases, a user-defined function provides a mechanism for extending the functionality of the database server by adding a function that can be evaluated in SQL statements.
The Function Code
Below is the complete function definition:
CREATE FUNCTION dbo.udf_ListToTable ( @LIST NVARCHAR(4000), @DELIMITER NVARCHAR(10) = ',' ) RETURNS @ListTable TABLE ( Item NVARCHAR(200) ) AS BEGIN DECLARE @LenDel INT DECLARE @Pos INT DECLARE @Item NVARCHAR(200) --Get the length of the delimiter, use hack to get around LEN(' ') = 0 issue SET @LenDel = LEN(@DELIMITER + '|') - 1 SET @Pos = CHARINDEX(@DELIMITER, @LIST) WHILE @Pos > 0 BEGIN --Get the item SET @Item = SUBSTRING(@LIST, 1, @Pos-1) --Add it to the table (if not empty string) IF LEN(LTRIM(@Item)) > 0 INSERT @ListTable (Item) VALUES (LTRIM(@Item)) --Remove the item from the list SET @LIST = STUFF(@LIST, 1, @Pos+@LenDel-1, '') --Get the position of the next delimiter SET @Pos = CHARINDEX(@DELIMITER, @LIST) END --Add the last item to the table (if not empty string) IF LEN(LTRIM(@LIST)) > 0 INSERT @ListTable (Item) VALUES (LTRIM(@LIST)) RETURN END GO
The function simply loops over the list passed into the function. Each list item is then inserted into the variable named @ListTable, which is of type TABLE. The @ListTable variable is then returned out of the function and can be handled the same as any other table.
The Function In Use
A simple demonstration is as follows:
INSERT INTO tableName (column1, column2, column3, column4) SELECT @variable1, @variable2, myTable.item, GETDATE() FROM dbo.udf_ListToTable(@list,',') AS myTable
In this example, we insert the same information (@variable1, @variable2) for every instance of an item found in myTable.
This is useful, for example, if you want to apply a setting to a group of users. The group of users could be contained in a list that needs to be parsed as a table, whilst the individual setting details are contained in the other variables.
Download the Code
Download the code, rename the file to .sql and run on your database instance. You will then be able to reference the function in your Stored Procedures.
Tags: array, data, database, extend, function, SQL, sub-routine, subroutine, t-sql, tabular, UDF, user defined function









No comments
Comments feed for this article
Trackback link: http://www.simonwhatley.co.uk/sql-user-defined-function-listtotable/trackback