經過一些研究後,我發現如何從字符串中刪除一系列不需要的字符。我正在計劃把它放在一個函數中,並在需要時調用它。刪除不需要的字符的函數 - 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