Conversion failed when converting from a character string to uniqueidentifier error in SQL Server

后端 未结 4 635
别跟我提以往
别跟我提以往 2020-12-20 12:15

I\'ve been getting the error \"Conversion failed when converting from a character string to uniqueidentifier\" and am finally at the end of my rope. I\'ve narrowed down my p

4条回答
  •  爱一瞬间的悲伤
    2020-12-20 12:47

    The use of this UDF is indeed making procedural assumptions about order of execution. It assumes that the WHERE clause inside the UDF will be evaluated before the cast(item as uniqueidentifier). This assumption is erroneous as the optimizer is free to change the plan to move the WHERE clause above the cast and the net effect is that the cast is asked to converts a partial token to a guid (ie. a string like 18E809E-EA7A-44B5-B230-776C42594D91).

    For a more detailed answer read T-SQL functions do no imply a certain order of execution.

    As a workaround you can force NULL into the projected values of the UDF for the rows that don't meet the WHERE clause:

    CREATE FUNCTION dbo.DelimitedSplit8K
    ...
    cteStart(N1, nullify) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                     SELECT t.N+1, 
                        case when (SUBSTRING(@pString,t.N,1) = @pDelimiter OR t.N = 0) then 1 else 0 end
                       FROM cteTally t
                      WHERE (SUBSTRING(@pString,t.N,1) = @pDelimiter OR t.N = 0) 
                    )
    --===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
     SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY s.N1),
            Item       = case s.nullify
                when 1 then SUBSTRING(@pString,s.N1,ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000))
                else null
                end
       FROM cteStart s;
    go
    

    Because the CASE expression is guaranteed to be evaluated before the CAST (since the input of the CAST is the output of the CASE) the reordering of the WHERE clause is safe.

提交回复
热议问题