将字符串替换为要加入的Id时无法JOIN表

时间:2014-07-04 11:02:31

标签: sql sql-server sql-server-2008

我有如下数据:

[Main].[Relation]
'SalesMan1'
'Supplier1'
'Customer2'

SQL查询:

SELECT * 
FROM [Main] [M]
INNER JOIN [SalesMan] [S]
ON [S].[Id] = Replace([M].[Relation],'SalesMan','')
WHERE [M].[Relation] LIKE 'SalesMan%'


Getting exeception :
**Conversion failed when converting the nvarchar value 'Supplier1' to data type int.**

请指导我如何解决它。

等待你宝贵的想法。

提前致谢。

1 个答案:

答案 0 :(得分:2)

而不是=使用LIKE

SELECT * 
FROM   [Main] [M] INNER JOIN 
       [SalesMan] [S] ON [S].[Id] = CAST(REPLACE([M].[Relation],'SalesMan','') AS INT)
WHERE  [M].[Relation] LIKE 'SalesMan%'