我收到错误消息“将nvarchar值‘23,24,3,45,91’转换为数据类型int时转换失败。” 该错误似乎发生在ON子句上。E.ID是一个整数字段,而F.LegalIssue是一个由逗号分隔的整数的varchar字段。下面是带有该错误的代码。
SELECT F.[FDTitle], E.PrimaryOpID as [FD Primary OP ID], F.County as [FD County], F.Status as [FD Status], F.IssueDate as [FD Date] FROM [dbo].[tbl_FinalDetMain] F LEFT OUTER JOIN [dbo].[tbl_lk_Exemptions_FD] E ON E.ID = F.LegalIssue WHERE F.[FDNbr] = '2013-0041'
我已经尝试过以下代码中的on子句,但是它仅返回一个整数值,而不是整个整数字符串。
E.ID = cast(LEFT(F.LegalIssue,PATINDEX('%[^0-9]%',F.LegalIssue)-1) as int)
结果应包括五个以逗号分隔的整数。
如果LegalIssue包含一串以逗号分隔的数字,那么您确实需要一个关联表。缺少这一点,这是进行联接的一种方便(但效率不高)的方法:
LegalIssue
SELECT F.[FDTitle], E.PrimaryOpID as [FD Primary OP ID], F.County as [FD County], F.Status as [FD Status], F.IssueDate as [FD Date] FROM [dbo].[tbl_FinalDetMain] F LEFT OUTER JOIN [dbo].[tbl_lk_Exemptions_FD] E ON ','+F.LegalIssue+',' like '%,'cast(E.ID as varchar(255))+',%' WHERE F.[FDNbr] = '2013-0041';
这会在列表前面加上逗号,以免产生冲突,例如在“ 1,100,1000”中找到“ 10”。