经过一些研究后,我发现如何从字符串中删除一系列不需要的字符。我正在计划把它放在一个函数中,并在需要时调用它。删除不需要的字符的函数 - SQL Server
但是,通常当我编程或编写代码时,我只是希望它能够正常工作,而不是工作得很好,所以我想知道如果你有SQL Server专家在那里看到任何可以使代码更优雅的东西,并且如果你能发现任何潜在的SQL注射问题:
IF OBJECT_ID('tempdb..#tmpMNHArrayOfChars') IS NOT NULL DROP TABLE #tmpMNHArrayOfChars
IF OBJECT_ID('tempdb..#ExcludedChars') IS NOT NULL DROP TABLE #ExcludedChars
GO
DECLARE @SomeString VARCHAR(300);
SET @SomeString = 'Fluffy=the_rab bit_';
DECLARE @Count INT;
SET @Count = 0;
DECLARE @Len INT;
SET @Len = LEN(@SomeString);
DECLARE @CharVal VARCHAR;
DECLARE @CharPos INT;
--Create a table for each char in the string
CREATE TABLE #tmpMNHArrayOfChars (CharPos INT, CharVal VARCHAR)
WHILE @Count <= @Len
BEGIN
SET @CharVal = RIGHT(LEFT(@SomeString, @Count),1)
INSERT INTO #tmpMNHArrayOfChars (CharPos, CharVal) VALUES (@Count, @CharVal)
SET @Count = @Count + 1;
END
-- Set up Tmp table of excluded chars
CREATE TABLE #ExcludedChars
(
CharId INT NOT NULL PRIMARY KEY,
CharString VARCHAR(12)
)
INSERT INTO #ExcludedChars (CharId, CharString)
VALUES
(001, '!'),
(002, '£'),
(003, '$'),
(004, '%'),
(005, '^'),
(006, '&'),
(007, '*'),
(008, '('),
(009, ')'),
(010, '_'),
(011, '+'),
(012, '='),
(013, '@'),
(014, '~'),
(015, '#'),
(016, '\'),
(017, '/'),
(018, '|'),
(019, '{'),
(020, '}'),
(021, '['),
(022, ']'),
(023, '<'),
(024, '>'),
(025, '.'),
(026, ','),
(027, '¬')
--Compare two tables and remove uneeded chars
DECLARE @SomeInt INT
DECLARE @SomeCount INT
DELETE SC FROM #tmpMNHArrayOfChars SC
CROSS JOIN #ExcludedChars EC WHERE SC.CharVal=EC.CharString
SELECT * FROM #tmpMNHArrayOfChars SC
expedted输出应该 – Chanukya
在性能方面,我不认为有一个更好的办法比嵌套'REPLACE'声明我害怕。 – Bridge
[字符映射/搜索和替换字符在SQL Server 2008 R2中的字符可能的重复](http://stackoverflow.com/questions/10070643/character-mapping-search-and-replace-character-by-character-in -sql-server-2008) – Bridge