我有一个标量UDF,负责在其中返回带有唯一字的NVARCHAR(MAX)
。不要问为什么。 :)
样品输入:“披萨pinapple萨拉米香肠披萨芝士奶酪”
样品输出:“披萨pinapple萨拉米香肠”。
这是UDF:
ALTER FUNCTION [dbo].[ToUniqueString]
(
@NonUniqueString NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @ReturnValue NVARCHAR(MAX)
-- Split the string by spaces.
DECLARE @Words TABLE (Word NVARCHAR(MAX))
INSERT INTO @Words
SELECT Word FROM dbo.SplitText(@NonUniqueString , ' ')
-- Cursor through the records, creating a unique string.
DECLARE @CurrentWord NVARCHAR(MAX)
DECLARE @UniqueString NVARCHAR(MAX) = ''
DECLARE WordCursor CURSOR FOR SELECT DISTINCT Word FROM @Words
OPEN WordCursor
FETCH NEXT FROM WordCursor INTO @CurrentWord
WHILE @@FETCH_STATUS = 0
BEGIN
SET @UniqueString = @UniqueString + ' ' + @CurrentWord
FETCH NEXT FROM WordCursor INTO @CurrentWord
END
CLOSE WordCursor
DEALLOCATE WordCursor
RETURN RTRIM(LTRIM(@UniqueString ))
END
可以在没有光标的情况下完成吗? WHILE
循环更有效吗?那么FOR XML
呢?
只是寻找达到要求的最有效方式。
答案 0 :(得分:2)
可以用[{1}}:
替换光标FOR XML