I was inspired by Remus to come up with my own solution as a table-valued function.
CREATE FUNCTION [dbo].[PARSE_SEARCH_STRING]
(
@search_string NVARCHAR(MAX)
)
RETURNS @table_token TABLE (
operator CHAR(1) NULL,
token NVARCHAR(MAX)
)
AS
BEGIN
DECLARE @token NVARCHAR(MAX)
DECLARE @operator CHAR(1)
DECLARE @remainder NVARCHAR(MAX)
DECLARE @length INTEGER
SET @remainder = LTRIM(RTRIM(@search_string))
WHILE LEN(@remainder) > 0
BEGIN
IF SUBSTRING(@remainder, 1, 1) = '-' OR SUBSTRING(@remainder, 1, 1) = '+' OR SUBSTRING(@remainder, 1, 1) = '='
BEGIN
SET @operator = LTRIM(RTRIM(SUBSTRING(@remainder, 1, 1)))
SET @remainder = LTRIM(RTRIM(SUBSTRING(@remainder, 2, LEN(@remainder) - 1)))
END
ELSE
SET @operator = NULL
IF SUBSTRING(@remainder, 1, 1) = '"'
BEGIN
SET @length = CHARINDEX('"', @remainder, 2) - 2
IF NOT @length > 0 SET @length = LEN(@remainder)
SET @token = LTRIM(RTRIM(SUBSTRING(@remainder, 2, @length)))
SET @remainder = LTRIM(RTRIM(SUBSTRING(@remainder, 3 + @length, LEN(@remainder) - @length + 2)))
END
ELSE
BEGIN
SET @length = CHARINDEX(' ', @remainder, 1) - 1
IF NOT @length > 0 SET @length = LEN(@remainder)
SET @token = LTRIM(RTRIM(SUBSTRING(@remainder, 1, @length)))
SET @remainder = LTRIM(RTRIM(SUBSTRING(@remainder, 1+ @length, LEN(@remainder) - @length + 2)))
END
IF NOT @token = ''
BEGIN
IF NOT EXISTS (
SELECT 1
FROM @table_token
WHERE operator = @operator
AND token = @token
)
INSERT @table_token ( operator, token ) VALUES ( @operator, @token )
END
END
RETURN
END