你可以這樣寫,將處理所有情況下的功能 - 有一個冒號(:
)和/或有一個分號(;
) - 或者根本沒有。在任何情況下,這將返回您要查找的字符串片段:
ALTER FUNCTION dbo.ExtractString (@InputString VARCHAR(500))
RETURNS VARCHAR(500)
AS BEGIN
DECLARE @Result VARCHAR(500)
DECLARE @ColonPos INT, @SemicolonPos INT
SET @ColonPos = CHARINDEX(':', @InputString)
SET @SemicolonPos = CHARINDEX(';', @InputString)
IF @ColonPos > 0
IF @SemicolonPos > 0
SET @Result = SUBSTRING(@InputString, @ColonPos + 1, @SemicolonPos - 1 - @ColonPos)
ELSE
SET @Result = SUBSTRING(@InputString, @ColonPos + 1, 500)
ELSE
IF @SemicolonPos > 0
SET @Result = SUBSTRING(@InputString, 1, @SemicolonPos - 1)
ELSE
SET @Result = @InputString
RETURN @Result
END
因爲它只是一個字符串處理函數,它不應該是在性能方面也不錯,無論是。
如果你運行它針對各種輸入:
SELECT
dbo.ExtractString('asp:test;abca'),
dbo.ExtractString('asps:tesst;abcsa'),
dbo.ExtractString('asssp:tsest;assbca'),
dbo.ExtractString('test'),
dbo.ExtractString('a:test'),
dbo.ExtractString('atest;something')
你得到這些結果:
test tesst tsest test test atest
如果數據不包含冒號和/或分號,您會期望什麼結果? – 2012-03-13 13:13:35
我強烈建議不要在數據庫中做任何事情,除了crud。數據庫用於**存儲**數據不用於**處理**!在應用程序端進行處理。如果'asp'和'test'和'abca'帶有一些含義,那麼將它們分成三列。規範化它! – Oybek 2012-03-13 13:15:44
@Gasastros我真的很抱歉,如果沒有冒號和分號,我想得到完整的字符串 – Moons 2012-03-14 04:10:02