CREATE FUNCTION [dbo].[FNC_MASK] ( @SRC_STRING VARCHAR(50)
, @PATTERN VARCHAR(100))
RETURNS NVARCHAR(MAX)
AS
/*
SELECT DBO.FNC_MASK('20120706145623', '####.##.##') -- 2012.07.06
SELECT DBO.FNC_MASK('20120706145623', '####-##-## ##:##:##') -- 2012-07-06 14:56:23
SELECT DBO.FNC_MASK('20120706', '####-##-## ##:##:##') -- 2012-07-06
SELECT DBO.FNC_MASK(NULL, '####-##-## ##:##:##') -- NULL
*/
BEGIN
DECLARE @P_IDX INT = 0
, @S_IDX INT = 1
IF @SRC_STRING IS NULL
RETURN NULL;
WHILE CHARINDEX('#', @PATTERN) > 0 AND LEN(SUBSTRING(@SRC_STRING, @S_IDX, 1)) > 0
BEGIN
SET @P_IDX = CHARINDEX('#', @PATTERN)
SET @PATTERN = STUFF(@PATTERN, @P_IDX, 1, SUBSTRING(@SRC_STRING, @S_IDX, 1))
SET @S_IDX = @S_IDX + 1
END
IF @@ERROR <> 0
RETURN NULL
--RETURN REPLACE(@PATTERN, '#', '')
RETURN LEFT(@PATTERN, @P_IDX)
END
GO
CREATE FUNCTION [dbo].[FNC_FORMAT_DT] ( @P_DATE DATETIME
, @P_PATTERN VARCHAR(100))
RETURNS NVARCHAR(MAX)
AS
/*
SELECT DBO.FNC_FORMAT_DT(GETDATE(), 'YYYY-MM-DD HH:MI:SS');
SELECT DBO.FNC_FORMAT_DT(REG_DT, 'YYYYMMDDHHMISS');
*/
BEGIN
IF @P_DATE IS NULL
RETURN NULL;
DECLARE @YYYY VARCHAR(4)
, @MM VARCHAR(2)
, @DD VARCHAR(2)
, @HH VARCHAR(2)
, @MI VARCHAR(2)
, @SS VARCHAR(2);
SELECT @YYYY = SUBSTRING(T.DT, 1, 4)
, @MM = SUBSTRING(T.DT, 5, 2)
, @DD = SUBSTRING(T.DT, 7, 2)
, @HH = SUBSTRING(T.DT, 9, 2)
, @MI = SUBSTRING(T.DT, 11, 2)
, @SS = SUBSTRING(T.DT, 13, 2)
FROM (SELECT FORMAT(ISNULL(@P_DATE, GETDATE()), 'yyyyMMddHHmmss') AS DT) T;
SET @P_PATTERN = REPLACE(@P_PATTERN, 'YYYY', @YYYY);
SET @P_PATTERN = REPLACE(@P_PATTERN, 'MM', @MM);
SET @P_PATTERN = REPLACE(@P_PATTERN, 'DD', @DD);
SET @P_PATTERN = REPLACE(@P_PATTERN, 'HH', @HH);
SET @P_PATTERN = REPLACE(@P_PATTERN, 'MI', @MI);
SET @P_PATTERN = REPLACE(@P_PATTERN, 'SS', @SS);
IF @@ERROR <> 0
SET @P_PATTERN = NULL
RETURN @P_PATTERN;
END