如何替换表格中的字符集?
ColumnA
%%1234UIT
!!1234TTT
678@@PPP
目前我正在使用
`replace(replace(replace([BLOCK_NAME],'%%',''),'!!',''),'@@',''),1,LEN(BLOCK_NAME)-1`
OR
replace(replace(replace(substring([BLOCK_NAME],1,LEN(BLOCK_NAME)-1),'**',''),'##',''),'$$','')
Expected OUTPUT: 1234UIT 123TTT 678PPP
答案 0 :(得分:1)
这应该适用于您的问题,它会从记录中删除所有非数字字符。您可以创建一个从查询中调用的sql函数。
WHILE PATINDEX('%[^0-9]%', @strText) > 0
BEGIN
SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')
END
RETURN @strText
答案 1 :(得分:1)
请参阅how to remove non-numeric/non-alphanumeric characters from string
CREATE FUNCTION [fnRemoveNonNumericCharacters](@strText VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN
WHILE PATINDEX('%[^a-z0-9]%', @strText) > 0
BEGIN
SET @strText = STUFF(@strText, PATINDEX('%[^a-z0-9]%', @strText), 1, '')
END
RETURN @strText
END
使用创建的函数选择数据
SELECT
dbo.fnRemoveNonNumericCharacters(BLOCK_NAME)
FROM
YourTable
OR
;WITH T as(
SELECT STUFF(BLOCK_NAME, PATINDEX('%[^a-z0-9]%', BLOCK_NAME), 1, '') BLOCK_NAME from YourTable
UNION ALL
SELECT STUFF(BLOCK_NAME, PATINDEX('%[^a-z0-9]%', BLOCK_NAME), 1, '') BLOCK_NAME from T where PATINDEX('%[^a-z0-9]%', BLOCK_NAME) > 0
)
select
*
from
T
where PATINDEX('%[^a-z0-9]%', BLOCK_NAME) = 0
我更喜欢使用CTE而没有用户定义函数的第二种方法。
答案 2 :(得分:1)
您可以创建一个函数:
CREATE FUNCTION [dbo].[fn_RemoveCharacters]
(
@Str NVARCHAR(MAX),
@MatchExpression VARCHAR(255)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
SET @MatchExpression = '%['+@MatchExpression+']%'
WHILE PatIndex(@MatchExpression, @Str) > 0
SET @Str = Stuff(@Str, PatIndex(@MatchExpression, @Str), 1, '')
RETURN @Str
END
Go
然后将其命名为:
SELECT [dbo].[fn_RemoveCharacters](ColumnA, '%%!!@@') as ColumnA
from table1
希望这有帮助!!!