1

我正在尝试对两个表执行内部联接,并且没有返回任何记录。两个表都在以 VARCHAR(50) 形式存储的邮政编码上进行连接。

    SELECT 
        T1.Name
       ,T1.PostalCode
       ,T2.Address
    FROM FirstTable as T1
        INNER JOIN SecondTable as T2 ON T1.PostalCode = T2.PostalCode

结果是没有记录被返回。我尝试从两个表中的邮政编码字段中修剪空白,但仍然没有结果。

然后,我尝试使用单独的 select 语句来缩小问题范围。下面的 select 语句返回带有邮政编码和地址的记录:

    SELECT PostalCode, Address, FROM SecondTable WHERE PostalCode = 'A1A1A1'

当我在第一个表上尝试此查询时,没有返回任何记录:

    SELECT Name, PostalCode FROM FirstTable WHERE PostalCode = 'A1A1A1'

这是非常令人困惑的,因为在 Excel 中手动查看表格会发现存在邮政编码的记录。

有人有想法吗?

4

3 回答 3

2

当我在第一个表上尝试此查询时,没有返回任何记录:

  SELECT Name, PostalCode FROM FirstTable WHERE PostalCode = 'A1A1A1'

好吧,你去。在此之前,联接也将不起作用。所以你有一些不好的数据。以下是一些您可以尝试帮助缩小问题范围的查询:

SELECT Name, PostalCode, Len(PostalCode) FROM FirstTable WHERE PostalCode LIKE '%A1A1A1'

SELECT Name, PostalCode, Len(PostalCode) FROM FirstTable WHERE PostalCode LIKE 'A1A1A1%'

SELECT Name, PostalCode, Len(PostalCode) FROM FirstTable WHERE PostalCode LIKE '%A1A1A1%'

SELECT Name, PostalCode, Len(PostalCode) FROM FirstTable WHERE PostalCode LIKE 'A%1A1A1%'

...以及同一主题的更多变体。

于 2013-08-15T14:23:32.587 回答
1

我最终使用您所有建议的混合找到了解决方案。问题是第一个表中的邮政编码末尾有一个隐藏的回车符。

/* See if any postal codes are more than 6 characters long. */
SELECT *, LEN(PostalCode)
FROM FirstTable
WHERE LEN(PostalCode) > 6

/* Find out the ASCII code for the hidden character. */
SELECT ASCII(RIGHT(PostalCode,1))
FROM FirstTable

/* Trimming hidden new line character (ASCII Code 13) from records. */
UPDATE FirstTable
SET PostalCode = REPLACE(PostalCode,CHAR(13),'')

感谢大家!

于 2013-08-15T15:14:58.863 回答
1

Its possible you may have hidden newline characters which trim will not remove.

Try running a query against the tables and check the length of the field to see if they match what your expecting.

SELECT Name, PostalCode, LEN(PostalCode)
FROM FirstTable
WHERE LEN(PostalCode) > 6 -- or whatever value.

To remove the newline characters.

UPDATE FirstTable SET PostalCode = SET REPLACE(REPLACE(PostalCode, CHAR(13), ''), CHAR(10), '')
于 2013-08-15T14:21:05.643 回答