我现在有同样的问题,我相信我的情况 - 你想比较两个超过 4000 个字符的字符串 - 是一种可能的情况:-)。在我的情况下,我从特定表的 NVARCHAR(MAX) 字段中的不同表中收集大量数据,以便能够使用全文搜索该数据。使用 MERGE 语句使该表保持同步,将所有内容转换为 NVARCHAR(MAX)。所以我的 MERGE 语句看起来像这样:
MERGE MyFullTextTable AS target
USING (
SELECT --Various stuff from various tables, casting it as NVARCHAR(MAX)
...
) AS source (IndexColumn, FullTextColumn)
ON (target.IndexColumn = source.IndexColumn)
WHEN MATCHED AND source.FullTextColumn NOT LIKE target.FullTextColumn THEN
UPDATE SET FullTextColumn = source.FullTextColumn
WHEN NOT MATCHED THEN
INSERT (IndexColumn, FullTextColumn)
VALUES (source.IndexColumn, source.FullTextColumn)
OUTPUT -- Some stuff
当全文数据大于 4000 个字符时,由于 LIKE 比较,这会产生错误。
所以我创建了一个进行比较的函数。虽然它不是防弹的,但它对我有用。您还可以将数据拆分为 4000 个字符的块,然后比较每个块,但对我来说(目前)比较前 4000 个字符和长度就足够了......
所以合并语句看起来像:
MERGE MyFullTextTable AS target
USING (
SELECT --Various stuff from various tables, casting it as NVARCHAR(MAX)
...
) AS source (IndexColumn, FullTextColumn)
ON (target.IndexColumn = source.IndexColumn)
WHEN MATCHED AND udfCompareTwoTexts(source.FullTextColumn, target.FullTextColumn) = 1 THEN
UPDATE SET FullTextColumn = source.FullTextColumn
WHEN NOT MATCHED THEN
INSERT (IndexColumn, FullTextColumn)
VALUES (source.IndexColumn, source.FullTextColumn)
OUTPUT -- Some stuff
函数看起来像:
ALTER FUNCTION udfCompareTwoTexts
(
@Value1 AS NVARCHAR(MAX),
@Value2 AS NVARCHAR(MAX)
)
RETURNS BIT
AS
BEGIN
DECLARE @ReturnValue AS BIT = 0
IF LEN(@Value1) > 4000 OR LEN(@Value2) > 4000
BEGIN
IF LEN(@Value1) = LEN(@Value2) AND LEFT(@Value1, 4000) LIKE LEFT(@Value2, 4000)
SET @ReturnValue = 1
ELSE
SET @ReturnValue = 0
END
ELSE
BEGIN
IF @Value1 LIKE @Value2
SET @ReturnValue = 1
ELSE
SET @ReturnValue = 0
END
RETURN @ReturnValue;
END
GO