您可以使用 SQL Server 的内置函数来执行此操作。本示例中使用的所有这些都存在于 SQL Server 2008 及更高版本中。
DECLARE @String VARCHAR(500) = 'Example Input: 1234567890, 1234, 12345, 123456, 1234567, 123asd456'
DECLARE @StartPos INT = 1, @EndPos INT = 1;
DECLARE @Input VARCHAR(500) = ISNULL(@String, '') + ' '; --Sets input field and adds a control character at the end to make the loop easier.
DECLARE @OutputString VARCHAR(500) = ''; --Initalize an empty string to avoid string null errors
WHILE (@StartPOS <> 0)
BEGIN
SET @StartPOS = PATINDEX('%[0-9][0-9][0-9][0-9][0-9]%', @Input);
IF @StartPOS <> 0
BEGIN
SET @OutputString += SUBSTRING(@Input, 1, @StartPOS - 1); --Seperate all contents before the first occurance of our filter
SET @Input = SUBSTRING(@Input, @StartPOS, 500); --Cut the entire string to the end. Last value must be greater than the original string length to simply cut it all.
SET @EndPos = (PATINDEX('%[0-9][0-9][0-9][0-9][^0-9]%', @Input)); --First occurance of 4 numbers with a not number behind it.
SET @Input = STUFF(@Input, 1, (@EndPos - 1), REPLICATE('*', (@EndPos - 1))); --@EndPos - 1 gives us the amount of chars we want to replace.
END
END
SET @OutputString += @Input; --Append the last element
SET @OutputString = LEFT(@OutputString, LEN(@OutputString))
SELECT @OutputString;
输出以下内容:
示例输入:******7890、1234、*2345、**3456、***4567、123asd456
这整个代码也可以作为一个函数,因为它只需要一个输入文本。