Skip to content

Instantly share code, notes, and snippets.

@dmtrek14
Created July 15, 2022 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmtrek14/6cf349a2d2a0e873c4c06c7ebd5f7e57 to your computer and use it in GitHub Desktop.
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.
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