比较一个函数中的两个nvarchar

时间:2014-09-04 04:52:03

标签: sql sql-server

在一个函数中我想检查传递的值是否等于预定义的值(@ValX)
我写了以下功能:

ALTER Function IsNotInReview(@Val NVARCHAR(MAX))
RETURNS BIT
AS
BEGIN
    DECLARE @ValX NVARCHAR(MAX)
    SET @ValX = '
{
"httpCode" : 200,
"message" : "OK",
"result" : {
    "items" : {
    "items" : [ ]
    }
}
}
    '

    IF LTRIM(RTRIM(@Val)) = LTRIM(RTRIM(@ValX))
    BEGIN
        RETURN 1
    END
    ELSE
    BEGIN
        RETURN 0
    END
    RETURN 0

END

当我测试调用函数时,我总是得到错误的值

SELECT dbo.IsNotInReview('
{
"httpCode" : 200,
"message" : "OK",
"result" : {
    "items" : {
    "items" : [ ]
    }
}
}
')--should return true

SELECT dbo.IsNotInReview('test')

更新

我已经更新了我的SP,但仍然得到了同样的错误'返回值

ALTER Function IsNotInReview(@Val NVARCHAR(MAX))
RETURNS BIT
AS
BEGIN
    DECLARE @ValX NVARCHAR(MAX)
    SET @ValX = '
{
"httpCode" : 200,
"message" : "OK",
"result" : {
    "items" : {
    "items" : [ ]
    }
}
}
    '

    DECLARE @ReturnVal BIT

    IF LTRIM(RTRIM(@Val)) = LTRIM(RTRIM(@ValX))
    BEGIN
        SET @ReturnVal = 1
    END
    ELSE
    BEGIN
        SET @ReturnVal = 0
    END
    RETURN @ReturnVal

END



SELECT dbo.IsNotInReview('{
  "httpCode" : 200,
  "message" : "OK",
  "result" : {
    "items" : {
      "items" : [ ]
    }
  }
}') --Return false which is unexpected

1 个答案:

答案 0 :(得分:1)

您没有比较相同的字符串。看看缩进。我无法想象这就是你的意图,即不仅要比较相关内容,还要比较缩进。

一种可能的解决方案是删除字符串中的所有空格,换行符等,同时跳过用双引号括起来的部分。

编辑:这是一个可能对你有用的小功能。它会在跳过引用区域时从字符串中删除空格。请彻底测试,我只写了一下并稍微测试一下(我现在必须去上班)

create function RemoveWhiteSpaces (@String nvarchar(max)) 
returns nvarchar(max)
as
begin
 declare @result nvarchar(max), @i int, @n int, @inQuotes bit, 
 declar @c0 nchar(1), @c nchar(1)

  set @i=1
  set @n=len(@string)
  set @result=''
  set @inQuotes=0
  set @c='x'

  while @i <= @n begin
    set @c0=@c
    set @c=substring(@string,@i,1)
    if @c='"' and @c0 != '\'
      set @inQuotes= 1 - @inQuotes

    if @inQuotes = 1 or 
      (@inQuotes = 0 and @c not in (' ',char(13), char(10),char(8))) 
      set @result = @result + @c

    set @i=@i+1
  end
  return @result
end
相关问题