gpt4 book ai didi

SQL Server 替换不在范围内的字符

转载 作者:行者123 更新时间:2023-12-05 00:28:32 25 4
gpt4 key购买 nike

我如何替换所有不在指定字符范围内的字符?

DECLARE @s VARCHAR(max)
DECLARE @allowedChars VARCHAR(max)
SET @s = 'Foo@Bar !'
SET @allowedChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ$_/+-.0123456789'

SELECT MAGICREPLACE(@s, @allowedChars,'_');
--Should return 'F___B____'

最佳答案

单程:

CREATE FUNCTION [dbo].MAGICREPLACE(@BUFFER VARCHAR(MAX), @PATTERN VARCHAR(128), @REPL VARCHAR(1)) RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @POS INT = PATINDEX(@PATTERN, @BUFFER COLLATE SQL_Latin1_General_CP1_CS_AS)
WHILE @POS > 0 BEGIN
SET @BUFFER = STUFF(@BUFFER, @POS, 1, @REPL)
SET @POS = PATINDEX(@PATTERN, @BUFFER COLLATE SQL_Latin1_General_CP1_CS_AS)
END
RETURN @BUFFER
END

为了
SELECT dbo.MAGICREPLACE('Foo@Bar !', '%[^ABCDEFGHIJKLMNOPQRSTUVWXYZ0-9$_/+-.]%', '_')

> F___B____

关于SQL Server 替换不在范围内的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40020865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com