我正在尝试删除表中多个列中的非字母数字字符,并且无权创建函数或临时函数。我想知道这里是否有人在不创建任何功能的情况下删除非字母数字字符有任何经验?谢谢。我正在使用MS SQL Server Management Studio v17.9.1
答案 0 :(得分:0)
这是一个起点-您需要对其进行调整以适应所有需要清洗的色谱柱:
O(len(str_))
从本质上讲,它是递归CTE,它将用空字符串(通过;WITH allcharcte ( id, textcol1, textcol2, textcol1where, textcol2where )
AS (SELECT id,
CAST(textcol1 AS NVARCHAR(255)),
CAST(textcol2 AS NVARCHAR(255)),
-- Start the process of looking for non-alphanumeric chars in each
-- of the text columns. The returned value from PATINDEX is the position
-- of the non-alphanumeric char and is stored in the *where columns
-- of the CTE.
PATINDEX(N'%[^0-9A-Z]%', textcol1),
PATINDEX(N'%[^0-9A-Z]%', textcol2)
FROM #temp
UNION ALL
-- This is the recursive part. It works through the rows which have been
-- returned thus far processing them for use in the next iteration
SELECT prev.id,
-- If the *where column relevant for each of the columns is NOT NULL
-- and NOT ZERO, then use the STUFF command to replace the char
-- at that location with an empty string
CASE ISNULL(prev.textcol1where, 0)
WHEN 0 THEN CAST(prev.textcol1 AS NVARCHAR(255))
ELSE CAST(STUFF(prev.textcol1, prev.textcol1where, 1, N'') AS NVARCHAR(255))
END,
CASE ISNULL(prev.textcol2where, 0)
WHEN 0 THEN CAST(prev.textcol2 AS NVARCHAR(255))
ELSE CAST(STUFF(prev.textcol2, prev.textcol2where, 1, N'') AS NVARCHAR(255))
END,
-- We now check for the existence of the next non-alphanumeric
-- character AFTER we replace the most recent finding
ISNULL(PATINDEX(N'%[^0-9A-Z]%', STUFF(prev.textcol1, prev.textcol1where, 1, N'')), 0),
ISNULL(PATINDEX(N'%[^0-9A-Z]%', STUFF(prev.textcol2, prev.textcol2where, 1, N'')), 0)
FROM allcharcte prev
WHERE ISNULL(prev.textcol1where, 0) > 0
OR ISNULL(prev.textcol2where, 0) > 0)
SELECT *
FROM allcharcte
WHERE textcol1where = 0
AND textcol2where = 0
)重复替换任何非字母数字字符(通过PATINDEX(N'%[^0-9A-Z]%', <column>)
找到)。通过复制这些块,您应该能够使其适应任何数量的列。
编辑:如果您希望有100多个非字母数字字符的实例要从任一列中删除,则需要在调用之前调整MAXRECURSION属性。
答案 1 :(得分:0)
如果您必须使用单个SELECT
查询(如提到的@ Forty3),则多个REPLACE
(如@ Gordon-Linoff)可能是最好的(但绝对不理想)。
如果您可以更新数据或使用T-SQL,则可以从https://searchsqlserver.techtarget.com/tip/Replacing-non-alphanumeric-characters-in-strings-using-T-SQL执行以下操作:
while @@rowcount > 0
update user_list_original
set fname = replace(fname, substring(fname, patindex('%[^a-zA-Z ]%', fname), 1), '')
where patindex('%[^a-zA-Z ]%', fname) <> 0