我不知道這是否是最有效的方法來解決您的問題,但想到的一點是封裝邏輯將輸入字符串拆分爲表值函數。
調用函數並將結果存儲到表變量中。
對錶變量進行迭代並將拆分字符串連接成用於搜索的最終字符串。
我還沒有列入該函數的代碼在這裏(爲簡潔起見),但對我來說我的函數接受分割字符串分隔符拆分的字符串並返回一個表具有以下結構:Position INT, Value VARCHAR(8000)
一旦你擁有了功能的地方,你可以將它類似於以下:
SET NOCOUNT ON
DECLARE @sampleString VARCHAR(500)
SET @sampleString = 'Jon Sidnell Rocks'
DECLARE @delimiter VARCHAR(20);
SET @delimiter = ' '
DECLARE @SplitResults TABLE (
POSITION INT,
VALUE VARCHAR(8000),
fUsed BIT DEFAULT 0)
INSERT INTO @SplitResults (POSITION, VALUE)
SELECT * FROM dbo.ufn_SplitString(@sampleString, @delimiter)
--Set up a simple loop instead of having to open up a cursor
DECLARE @Value VARCHAR(8000);
DECLARE @Position INT;
SELECT @Value = q.VALUE, @Position = q.Position
FROM (SELECT TOP 1 VALUE, Position FROM @SplitResults WHERE fUsed = 0)q
DECLARE @SearchString VARCHAR(8000)
WHILE @@ROWCOUNT <> 0 AND @Value IS NOT NULL
BEGIN
IF @Position = 1
BEGIN
SET @SearchString = '("' + @Value + '*" OR FORMSOF(THESAURUS, '+ @Value +') OR FORMSOF(INFLECTIONAL, ' + @Value + '))'
END
ELSE
BEGIN
SET @SearchString = @SearchString + ' OR ("' + @Value + '*" OR FORMSOF(THESAURUS, '+ @Value +') OR FORMSOF(INFLECTIONAL, ' + @Value + '))'
END
--Update record so we know we used it
UPDATE @SplitResults SET fUsed = 1
WHERE Position = @Position AND VALUE = @Value
--Get Next Value to Work With
SELECT @Value = q.VALUE, @Position = q.Position
FROM (SELECT TOP 1 VALUE, Position FROM @SplitResults WHERE fUsed = 0)q
END
PRINT @SearchString;
SET NOCOUNT OFF;
輸出應該是這個樣子:
("Jon*" OR FORMSOF(THESAURUS, Jon) OR FORMSOF(INFLECTIONAL, Jon)) OR ("Sidnell*" OR FORMSOF(THESAURUS, Sidnell) OR FORMSOF(INFLECTIONAL, Sidnell)) OR ("Rocks*" OR FORMSOF(THESAURUS, Rocks) OR FORMSOF(INFLECTIONAL, Rocks))
啊,我忘記了SQL Server中的CLR代碼。這實際上似乎是一個非常好的選擇,雖然性能有點不明。將不得不看更接近... – jonsidnell 2011-05-11 09:16:17