SQL选择Len - 转换失败?

时间:2014-02-25 16:18:09

标签: sql type-conversion patindex

这是我的疑问:

SELECT at.AssetTag, 
dp.Custodian,
CASE WHEN PATINDEX('%_%', dp.Custodian) = '0'
THEN dp.Custodian 
ELSE RIGHT(LTRIM(RTRIM(dp.Custodian)),LEN(LTRIM(RTRIM(dp.Custodian)) - PATINDEX('%_%', dp.Custodian))) END AS FirstName, 
CASE WHEN PATINDEX('%_%', dp.Custodian) = '0' 
THEN '' 
ELSE LEFT(dp.Custodian, PATINDEX('%_%', dp.Custodian)-1) END AS LastName, RIGHT(at.Assettag,3) AS MediaTypeSuffix
FROM tblAssetTracking at (NOLOCK) 
INNER JOIN tblDiscoveryProcessing dp (NOLOCK) ON dp.FKAsset = at.ID 
WHERE dp.Custodian Is Not Null

当我运行它时,我收到错误“将nvarchar值'XXX'转换为数据类型int时转换失败”(xxx是我必须替换的实际值)。有人可以帮忙吗? PS。我希望声明进入代码块。显然,我不明白如何正确粘贴代码。

谢谢!

1 个答案:

答案 0 :(得分:0)

没关系。我不得不删除修剪:

SELECT at.AssetTag, 
dp.Custodian, 
CASE WHEN PATINDEX('%[_]%', dp.Custodian) = '0'
    THEN dp.Custodian 
    ELSE RIGHT(dp.Custodian,LEN(dp.Custodian) - PATINDEX('%[_]%', dp.Custodian))
END AS FirstName, 
CASE WHEN PATINDEX('%[_]%', dp.Custodian) = '0' 
    THEN '' 
    ELSE LEFT(dp.Custodian, PATINDEX('%[_]%', dp.Custodian)-1) 
END AS LastName, 
RIGHT(at.Assettag,3) AS MediaTypeSuffix
FROM tblAssetTracking at (NOLOCK)
INNER JOIN tblDiscoveryProcessing dp (NOLOCK) ON dp.FKAsset = at.ID
WHERE dp.Custodian Is Not Null