错误:传递给LEFT或SUBSTRING函数的长度参数无效

时间:2013-09-23 12:35:42

标签: sql sql-server sql-server-2008 function sql-server-2005

我的功能如下::


Create Function dbo.fnFcid(@url varchar)
 Returns int

 As

 BEGIN
 Return ( select ID from  TTI_fat.dbo.FormContext
          where caseId = (SELECT SUBSTRING(@url, PATINDEX('%&c=%', @url)+ 3, (PATINDEX('%&y=%', @url) - (PATINDEX('%&c=%', @url)+3)))) 
          and   YearID = (SELECT SUBSTRING(@url, PATINDEX('%&y=%', @url)+ 3, (PATINDEX('%&e=%', @url) - (PATINDEX('%&y=%', @url)+3)))) 
          and   EntityID = (SELECT SUBSTRING(@url, PATINDEX('%&e=%', @url)+ 3, (PATINDEX('%&g=%', @url) - (PATINDEX('%&e=%', @url)+3))))
          and   GroupID = (SELECT SUBSTRING(@url, PATINDEX('%&g=%', @url)+ 3, (PATINDEX('%&v=%', @url) - (PATINDEX('%&g=%', @url)+3)))) 
         )  
   END;
 Go

当我将以下值传递给函数


select dbo.fnFcid('http://localh0st/web/forms/getForm.asp?page=FKYASDENPLFPg1V2014&c=9&y=283&e=1022&g=2&v=1&x=296807&j=161037&z=1')

它显示我跟随错误


Msg 537, Level 16, State 2, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.

3 个答案:

答案 0 :(得分:1)

问题修正了我的上述问题 因为我忘了在声明函数时提到varchar大小

Create Function dbo.fnFcid(@url varchar(max))

答案 1 :(得分:0)

您的Substring表达式是导致错误的原因。

子串语法是 SUBSTRING(表达式,开始,长度)

您的长度部分代码是:

(PATINDEX('%&y=%', @url) - (PATINDEX('%&c=%', @url)+3))    

如果 @url 不包含&y=&c=,则长度将变为 -3

因此,由于负长度,tsql会产生错误。

处理否定部分,它将无误地运行。

答案 2 :(得分:0)

您是否错过了varchar的长度,如果您没有提及它的长度为1。

Create Function dbo.fnFcid(@url varchar(255))
 Returns int

 As

 BEGIN
 Return ( select ID from  TTI_fat.dbo.FormContext
          where caseId = (SELECT SUBSTRING(@url, PATINDEX('%&c=%', @url)+ 3, (PATINDEX('%&y=%', @url) - (PATINDEX('%&c=%', @url)+3)))) 
          and   YearID = (SELECT SUBSTRING(@url, PATINDEX('%&y=%', @url)+ 3, (PATINDEX('%&e=%', @url) - (PATINDEX('%&y=%', @url)+3)))) 
          and   EntityID = (SELECT SUBSTRING(@url, PATINDEX('%&e=%', @url)+ 3, (PATINDEX('%&g=%', @url) - (PATINDEX('%&e=%', @url)+3))))
          and   GroupID = (SELECT SUBSTRING(@url, PATINDEX('%&g=%', @url)+ 3, (PATINDEX('%&v=%', @url) - (PATINDEX('%&g=%', @url)+3)))) 
         )  
   END;
 Go