Posted by: tzuhsun | February 13, 2009

UDF, User Defined Functions in MSSQL

There are three types of UDF (refer to reference), however I will talk about Scalar UDF  here (Which means that function only return single value, you may refer to reference links below for other types).

UDF is quite useful for sometimes, ok, lets go to the point:

Environment:

  1. MS SQL Server 2000 or above.
  2. Northwind sample database from Microsoft.

Objective:

  • List all products in ONE row according to supplier id.

You can try it without UDF, do post your method if you know how to do that.

Here is the part of Product data:

Northwind - ProductsNorthwind – Products

First: We need to create a function to concat all product names into one line for each supplier id.


USE NORTHWIND
go

CREATE FUNCTION dbo.ConcatProductName (@sSupplierID as varchar(5))
RETURNS VARCHAR(1000)
AS
BEGIN

   DECLARE @sProduct as varchar(500)

   SET @sProduct = ''

   SELECT @sProduct = @sProduct + ProductName + ', ' FROM PRODUCTS
   WHERE SupplierID = @sSupplierID
   --	group by ProductName

   SET @sProduct = Left(@sProduct, Len(RTrim(@sProduct)) - 1)

   RETURN @sProduct
END

Second: Run and create the function above.

Third: Run the query below the check the result:


Select dbo.ConcatProductName(SupplierID) as ProductName

, SupplierID

From Products

Group by SupplierID

-- drop function ConcatProductName

Query with UDFQuery with UDF

See? It work great.

Refer to references below to know pros & cons, and more details about UDF.

References:

Northwind & pubs sample database from Microsoft.

User Defined Functions in Microsoft SQL Server 2000

User Defined Functions

Keywords: Customize function in MSSQL


Responses

  1. If you are using SQL 2005 and above, you can achieve it in a single query without UDF

    SELECT SupplierID, Product FROM Products AS P CROSS APPLY (SELECT ProductName + ‘,’ FROM Products WHERE SupplierID = P.SupplierID) FOR XML PATH(”)) AS DUMMY(Product)

  2. Some typo on previous comment. The correct query should be shown as following:

    SELECT SupplierID, ISNULL(SUBSTRING(Product, 1, DATALENGTH(Product) / 2 – 1), ”) FROM Products AS P CROSS APPLY (SELECT ProductName + ‘,’ FROM Products WHERE SupplierID = P.SupplierIDFOR XML PATH(”)) AS DUMMY(Product)

  3. 哈哈路人甲,知道你是谁了,上次喝酒过后你讲路人甲时我还不知道你在讲什么。

    下面讲回主题,给别人看的,哈哈。

    Thanks. I need some time to understand your query because I never write query using that way.


Leave a response

Your response:

Categories