Building on the vein of representing one-to-many relationships I've always been frustrated trying to display child records in tables and datagrids. Examples include showing multiple authors of publications, children in a classroom, and fish species observed in a lake.
Until today the two best methods I had were both hacks.
Method 1
Use Three Queries
1.) Build a crosstab
2.) Concatenate the output of the crosstab
3.) Join the product back to the parent table
- or -
Method 2
Loop through child records programmatically to build a comma-delimited list.
Today I discovered a far more elegant solution using COALESCE within a User Defined Function to build comma-delimited list in Views and Stored Procedures.
For this example we'll be building a comma-delimited list of fish species observed in each water (lakes and streams).
Step 1: Create a new User Defined Function(UDF)
Step 2: Call the User Defined Function in a View
Result:
...
Link
Until today the two best methods I had were both hacks.
Use Three Queries
1.) Build a crosstab
2.) Concatenate the output of the crosstab
3.) Join the product back to the parent table
- or -
Loop through child records programmatically to build a comma-delimited list.
Today I discovered a far more elegant solution using COALESCE within a User Defined Function to build comma-delimited list in Views and Stored Procedures.
For this example we'll be building a comma-delimited list of fish species observed in each water (lakes and streams).
Step 1: Create a new User Defined Function(UDF)
CREATE FUNCTION dbo.udf_GetFishByWater(@WaterID int)
RETURNS VARCHAR(1000) AS
BEGIN
DECLARE @FishList varchar(1000)
SELECT @FishList = COALESCE(@FishList + ', ', '') + SpeciesName
FROM VU_FishSpeciesByWater
WHERE WaterID = @WaterID
RETURN @FishList
END
Step 2: Call the User Defined Function in a View
SELECT WaterName As Stream, Parent,
dbo.udf_GetFishByWater(WaterID) as FishSurveyed
FROM GIS_Hydrography
Result:
Stream | Parent | FishSurveyed |
---|---|---|
Abbott Gulch | S. Fk. Boise River | Redbank Trout, Sculpin (Var. Species) |
Adair Creek | Jungle Creek | Cutthroat Trout, Westslope Cutthroat Trout |
Adams Creek | Mann Creek | Rainbow / Redband Trout (Wild), Rainbow Trout |
Agency Creek | Lemhi River | Bull Trout, Cutthroat Trout, Rainbow Trout, Sculpin (Var. Species) |
Ahrs Gulch | Saint Joe River | Brook Trout, Cutthroat Trout |
Airplane Lake | Ship Island Creek | Cutthroat Trout, Rainbow Trout |
Alder Creek | Morgan Creek | Cutthroat Trout, Rainbow / Redband Trout (Wild), Rainbow X Cutthroat Trout |
Alder Creek | Patterson Creek | Bull Trout, Cutthroat Trout, Rainbow / Redband Trout (Wild), Rainbow X Cutthroat Trout, Unknown Species |
Alder Creek | S. Fk. Payette River | Dace (Var. Sp.), Rainbow Trout, Sucker (Var. Sp.) |
Link
NOTE: These are now stored as Scalar-valued Functions in SQL Server 2008
Comments