[英]SQL JOIN using Concatenated Field
I have two tables, Table1 contains a column with what constitutes a partial value of a column in Table2, for example: 我有两个表,表1包含一列,该表构成表2中列的部分值,例如:
Table1.XName = "123456" Table2.ZName = "ABC-123456"
Table1.XName =“ 123456” Table2.ZName =“ ABC-123456”
I need to create a JOIN that matches these up, but with MS-SQL 2008 I'm having trouble making this work. 我需要创建一个与之匹配的JOIN,但是使用MS-SQL 2008时,我很难做到这一点。 Here's a sample of my attempt:
这是我的尝试的一个示例:
SELECT * FROM Table1 LEFT OUTER JOIN Table2 ON ('ABC-'+Table1.XName)=Table2.ZName
SELECT * FROM Table1左外部联接Table2 ON('ABC-'+ Table1.XName)= Table2.ZName
It doesn't matter what type of JOIN I use, or in which direction either, it fails. 我使用哪种类型的JOIN都无关紧要,或者在哪个方向都失败了。 I know I'm doing something boneheaded here so if anyone can point me in the right direction I would appreciate it.
我知道我在这里做的事很卑鄙,所以如果有人能指出我正确的方向,我将不胜感激。
This works for me: 这对我有用:
DECLARE @Table1 TABLE (XName VARCHAR(200))
DECLARE @Table2 TABLE (ZName VARCHAR(200))
INSERT
INTO @Table1
VALUES ('123456')
INSERT
INTO @Table2
VALUES ('ABC-123456')
SELECT *
FROM @Table1
LEFT JOIN
@Table2
ON ZName = 'ABC-' + XName
---
123456 ABC-123456
Could you please post the definitions of your tables and the error message you get? 您能否发布表的定义以及收到的错误消息?
Random guess... 随机猜测...
Table1.XName
datatype is a number (not character based) so you get conversion errors Table1.XName
数据类型是数字(不是基于字符的),因此会出现转换错误
SELECT * FROM
Table1
LEFT OUTER JOIN
Table2 ON 'ABC-' + CAST(Table1.XName as varchar(30)) = Table2.ZName
Try using 尝试使用
SELECT
*
FROM
Table1 LEFT OUTER JOIN Table2 ON
Table1.XName LIKE CONCAT("%", Table2.ZName, "%") OR
Table2.XName LIKE CONCAT("%", Table1.ZName, "%")
Please mark the answer if that works for you. 如果适合您,请标记答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.