与 SQL 中的 LIKE 条件匹配的空字符串变量

Empty string variable matching to LIKE conditions in SQL

我有一个 SQL 服务器 table 包含一个 nvarchar(max) 列。我 运行 查询 select 此列包含字符串 'remove' 的每一行。在结果中,我有几行此列填充了一个空字符串,我不明白为什么会返回这些值。

我试图进一步调查返回的空字符串值之一。我发现空字符串值会匹配某些 LIKE 条件,但不会匹配其他条件。例如,它将匹配 %remove%%x%,但不会匹配 %q%.

在 SQL Server Management Studio 的结果网格中,nvarchar 字段显示为空字段(不为空)。但是,如果我将 len() 函数应用于此字段,它 returns 的值为 649。当我将结果 table 从 SQL Server Management Studio 导出到 Excel,nvarchar(max) 字段为空。

假设一定有一堆空白字符填充该字段,我在将 'x' 连接到返回值的两端后尝试 select 该字段。在结果中,前导 'x' 出现在字符串的开头,但未显示连接到末尾的 'x'。

我对发生的事情一头雾水。我可以根据要求提供更多信息。

select itemid, content
from objects
where itemid = 100 and content like '%remove%'

----------------


itemid  |  content
100     |  

select itemid, 'x' + content + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------


itemid  |  content
100     |  x

编辑:

修剪字段不会改变字符数。但是,当我确实使用子字符串 select 串联输出中的最后一个字符时,返回的字符是 'x',这表明由于细绳。不过,在将内容导出到 Excel 时,我仍然看不到这个尾随 'x' 字符。我认为 nvarchar 变量中可能存在不受支持的字符。


select itemid, 'x' + ltrim(rtrim(content)) + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------


itemid  |  content
100     |  x

我认为,你应该trim专栏;

select itemid, LTRIM(RTRIM(content))
from objects
where itemid = 100 and content like '%remove%'

我猜你的字符串中有一些控制字符。例如,如果第一个字符是换行符,则可能导致不显示其余字符。

尝试

select item_id, unicode(content) 
from objects
where item_id = 100;

这将显示您可以看到第二个字符的第一个字符的 unicode 代码点:

unicode(substring(item, 2, 1))

等等。