Skip to content

Instantly share code, notes, and snippets.

@ConstantineK
Created January 9, 2019 00:27
Show Gist options
  • Save ConstantineK/f821161d7ce37b9a4cf71296afc42f82 to your computer and use it in GitHub Desktop.
Save ConstantineK/f821161d7ce37b9a4cf71296afc42f82 to your computer and use it in GitHub Desktop.
support index based masking strings in TSQL
-- You can either pass a format string, or you could store it in a table per row
-- If you want to support additional cases, just modify the last CROSS APPLY
DECLARE @format_string nvarchar(500) = 'X###XXX###'
SELECT STRING_AGG(result.chars,'') AS strings
FROM sys.objects AS m
CROSS APPLY
(
SELECT
DISTINCT
number
FROM master..spt_values AS v
WHERE
v.number BETWEEN 1 and LEN(m.name)
) AS num
CROSS APPLY
(
SELECT
SUBSTRING(m.name, num.number, 1) AS entity_data,
SUBSTRING(@format_string, num.number, 1) AS format_data
) AS comp
CROSS APPLY
(
SELECT
CASE
WHEN comp.format_data = '#'
THEN comp.entity_data
WHEN comp.format_data = 'x'
THEN comp.format_data
ELSE comp.entity_data
END AS chars
) AS result
GROUP BY
m.object_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment