-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdbo.udf_array_sort.sql
More file actions
70 lines (54 loc) · 3.56 KB
/
Copy pathdbo.udf_array_sort.sql
File metadata and controls
70 lines (54 loc) · 3.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
USE [NBA]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*------------------------------------------------------------------------------
Function Name: [dbo].[udf_array_sort]
Purpose: Sorts elements in a delimited string array and returns a delimited string
Project: T-SQL-Scripts
Date Created: 2025-10-15
Author: Ludwig Mark
Parameters:
@input - NVARCHAR(MAX) - Source array string
@delimiter - NCHAR(1) - Delimiter character between elements
Returns: NVARCHAR(MAX)
Notes:
- Trims elements and sorts them using default collation
- Uses STRING_AGG WITHIN GROUP for ordering
- Order is case-sensitive depending on database collation
Performance:
- Execution time: O(n log n) due to sorting
- Memory usage: Proportional to number of elements
Dependencies:
- Requires STRING_SPLIT (SQL Server 2016+)
- Requires STRING_AGG (SQL Server 2017+)
Example:
------------------------
SELECT dbo.udf_array_sort('b;A;c;d', ';') AS Sorted
Returns: 'A;b;c;d' (depending on collation)
Modification History:
Date Author Description
---------- ---------- ------------------------------------------------
2025-10-15 Ludwig M. Initial creation
Validation:
- Returns NULL if @input is NULL
- Handles empty elements correctly
LICENSE: MIT
------------------------------------------------------------------------------*/
CREATE FUNCTION [dbo].[udf_array_sort] (
@input NVARCHAR(MAX)
, @delimiter NCHAR(1)
) RETURNS NVARCHAR(MAX) AS
BEGIN
RETURN (
SELECT STRING_AGG(value, @delimiter) WITHIN GROUP (ORDER BY value)
FROM (
SELECT TOP (100) PERCENT value = LTRIM(RTRIM(value))
FROM STRING_SPLIT(@input, @delimiter)
ORDER BY value
) P
)
END
GO