TSQL Azure SQL Server LEFT CHARINDEX

时间:2015-10-07 22:10:26

标签: c# sql-server tsql azure

我有一个TSQL语句,查询单个表以查找重复的街道地址编号。例如,“123 Street”匹配“123 St.”。我使用CHARINDEX通过选择字符串左边的字符来分隔字符串,但是在空格之前几乎总是数字,如下所示:

    "SELECT NewId() as NewId," +
            //We rename the dbo.User table as "a" then rename it again as "b" so we can look for duplicate Street Address numbers
            "a.Id AS LeftID,a.DateSubmitted AS LeftDateSubmitted,a.Updated AS LeftUpdated," +
            "a.Status AS LeftStatus,a.StreetAddress AS LeftStreetAddress," +

            "b.Id AS RightID,b.DateSubmitted AS RightDateSubmitted,b.Updated AS RightUpdated," +
            "b.Status AS RightStatus,b.StreetAddress AS RightStreetAddress " +

            //We join the 2 virtual dbo.User tables where table b Id's are greater than table a meaning b records are newer
            "FROM [User] a JOIN [User] b ON b.Id > a.Id AND " +

            //LEFT selects the left most characters (usually numbers) in the StreetAddress field string before the space ' '
            //and eliminates the rest of the address isolating just the street address numbers for matching
            "LEFT(a.StreetAddress,CHARINDEX(' ',a.StreetAddress)) = LEFT(b.StreetAddress,CHARINDEX(' ',b.StreetAddress)) " +

            //Don't show orange or blue status records
            "AND b.Status != 'Orange' AND a.Status != 'Orange' AND a.Status != 'Blue' AND b.Status != 'Blue' " +

            //If a b record (newer) is red then ignore because it is completed and ignore a records (oldest) older than 90 days
            "WHERE a.DateSubmitted >= (GetDate() - 90) AND b.Status != 'Red' " +

            //Show newest records first
            "ORDER BY b.DateSubmitted DESC"

这一直运作良好,直到今天才注意到,如果该人以全部大写字母输入地址,则会收到误报:如下所示: Grid View

我对使用的理解:

    LEFT(a.StreetAddress,CHARINDEX(' ',a.StreetAddress))

在我的JOIN使用空格之前会产生最左边的字符但是上面的图像显示不应该出现的匹配吗?请帮助SQL初学者......

1 个答案:

答案 0 :(得分:1)

我不认为您要发送到数据库服务器以获取这些结果的查询是您使用该代码生成的确切查询。它不仅不正确地匹配地址......您还可以看到ID中的b小于a。设置一个断点,将查询发送到服务器并检查查询字符串并验证您实际发送的内容。