经过一番研究后,我发现了如何从字符串中删除一系列不需要的字符。我打算把它扔进一个函数中并在需要时调用它。
然而,通常当我编程或编写代码时,我只是想让它工作而不是运行良好,所以我想知道你是否有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
答案 0 :(得分:0)
DECLARE @SomeString VARCHAR(300);
SET @SomeString = 'Fluffy=the_rab bit_';
SELECT CONVERT (VARCHAR,
(SELECT SUBSTRING(@SomeString,sv.number,1) FROM master.dbo.spt_values AS sv
WHERE sv.type='P' AND sv.number BETWEEN 1 AND LEN(@SomeString)
AND NOT EXISTS(SELECT 0 FROM #ExcludedChars AS e WHERE e.CharString= SUBSTRING(@SomeString,sv.number,1))
FOR XML PATH(''),TYPE)
)