使用子串/左函数时,左连接与内连接会导致不同的结果

时间:2017-06-14 19:29:41

标签: sql tsql substring

是否有人能够解释为什么以下查询返回结果集:

SELECT sub.*, xr.*
FROM (
    select  rc.CommentID,
            [CreateDate] = LEFT(rc.Comments, 10),
            [CreatedBy] = SUBSTRING(rc.Comments, 12, CHARINDEX(':', rc.Comments) - 12),
            src.Comments
    from dbo.RequestComments rc
    where rc.CommentID NOT IN( 4290, 4289, 4221)
) sub
LEFT JOIN dbo.SWDBCWUserXRef xr
 ON sub.CreatedBy = xr.EnteredByName

...但是,如果我修改它以使用INNER JOIN而不是LEFT JOIN:

SELECT sub.*, xr.*
FROM (
    select  rc.CommentID,
            [CreateDate] = LEFT(rc.Comments, 10),
            [CreatedBy] = SUBSTRING(rc.Comments, 12, CHARINDEX(':', rc.Comments) - 12),
            src.Comments
    from dbo.RequestComments rc
    where rc.CommentID NOT IN( 4290, 4289, 4221)
) sub
JOIN dbo.SWDBCWUserXRef xr
 ON sub.CreatedBy = xr.EnteredByName 

我收到以下错误:

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

感谢。

1 个答案:

答案 0 :(得分:0)

SELECT sub.*, xr.*
FROM (
select  rc.CommentID,
[CreateDate] = LEFT(rc.Comments, 10),
[CreatedBy] = SUBSTRING(rc.Comments, 12, CHARINDEX(':', rc.Comments) - 12),
src.Comments
from dbo.RequestComments rc
where rc.CommentID NOT IN( 4290, 4289, 4221)
) sub
JOIN dbo.SWDBCWUserXRef xr
 ON SUBSTRING(rc.Comments, 12, CHARINDEX(':', rc.Comments) =    xr.EnteredByName