Created
July 15, 2022 16:56
-
-
Save dmtrek14/6cf349a2d2a0e873c4c06c7ebd5f7e57 to your computer and use it in GitHub Desktop.
Sample SQL script of a STUFF. In this example, there is a Deadlines table and if a date has more than one deadline, we want a single row per date and all deadlines to be in a comma-separated list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SET ANSI_NULLS ON | |
GO | |
SET QUOTED_IDENTIFIER ON | |
GO | |
-- ============================================= | |
-- Description: Returns table with deadlines. | |
-- If there's more than one deadline on a date, all are added to a single row and are comma separated | |
-- ============================================= | |
CREATE FUNCTION [dbo].[Deadlines] | |
( | |
) | |
RETURNS TABLE | |
AS | |
RETURN | |
( | |
SELECT DISTINCT dd.DeadlineDate | |
, STUFF(( | |
SELECT ', ' + dd2.DeadlineDescription | |
FROM [dbo].[DeadlineDay] dd2 | |
WHERE dd2.DeadlineDate = dd.DeadlineDate | |
ORDER BY dd2.DeadlineDate | |
FOR XML PATH('')), 1, 2, '' | |
) AS Deadline | |
FROM [dbo].[DeadlineDay] dd | |
); | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment