I have a table as:
I want to have a select statement to group records by itemID and one itemID will have only one row, multiple tagIDs will be combined in one field.
Step1: create a scalar-valued function (UDF)
ALTER FUNCTION sUDF_itemTagIds(@aItemId int)
DECLARE @tagids varchar(max)
SELECT @tagids = COALESCE(@tagids + ‘,’,”) + convert(varchar(20),tagID)
WHERE itemID = @aItemId
Step2: call the UDF from the SQL script:
SELECT itemID,dbo.sUDF_itemTagIds(itemID) as tagIDs
GROUP BY itemID
Here is the result:
Intro to User Defined Functions
The ability to create a user-defined function (UDF) is a new feature added to SQL Server 2000.
A user-defined function is a database object that encapsulates one or more Transact-SQL statements for reuse. This definition is similar to the one for stored procedures, but there are many important differences between user-defined functions and stored procedures—the most pronounced being what types of data they can return.
A scalar function returns a single value of the data type referenced in the RETURNS clause of the CREATE FUNCTION statement. The returned data can be of any type except text, ntext, image, cursor, or timestamp.
Inline Table-Valued Functions
An inline table-valued function returns a variable of data type table whose value is derived from a single SELECT statement.
Multi-Statement Table-Valued Functions
The multi-statement table-valued function is slightly more complicated than the other two types of functions because it uses multiple statements to build the table that is returned to the calling statement. Unlike the inline table-valued function, a table variable must be explicitly declared and defined.
Returns the first nonnull expression among its arguments.
COALESCE ( expression [ ,...n ] )