CHARINDEX怪异

时间:2018-08-17 19:06:58

标签: sql tsql

您如何看待以下结果?

SELECT CHARINDEX('space and /* comment */', 'Phrase with space and /* comment */') AS MatchPosition;
DECLARE @SearchWord varchar =  'space and /* comment */'
SELECT CHARINDEX(@SearchWord, 'Phrase with space and /* comment */') AS MatchPosition;
SELECT CHARINDEX(@SearchWord, 'Phrase with space and comment') AS MatchPosition;

我期望结果1和2相同,结果3为零,但实际上结果2和3相同,并且它们也不为零,也不等于结果1。

这是怎么回事?

我没有看到这样的预防措施 https://docs.microsoft.com/en-us/sql/t-sql/functions/charindex-transact-sql?view=sql-server-2017

1 个答案:

答案 0 :(得分:7)

捕获在这里:

DECLARE @SearchWord varchar =  'space and /* comment */'
SELECT @SearchWord;
-- s
  

来自char and varchar

     

“当在数据定义或变量声明语句中未指定n时,默认长度为1。

应该是:

-- defining size to avoid implicit truncating
DECLARE @SearchWord varchar(100) =  'space and /* comment */'
SELECT @SearchWord;

  

我期望结果1和2相同,结果3将为零

正确。

SELECT CHARINDEX('space and /* comment */', 'Phrase with space and /* comment */') AS MatchPosition;
DECLARE @SearchWord varchar(100) =  'space and /* comment */'
SELECT CHARINDEX(@SearchWord, 'Phrase with space and /* comment */') AS MatchPosition;
SELECT CHARINDEX(@SearchWord, 'Phrase with space and comment') AS MatchPosition;

Rextester Demo