【问题标题】:TSQL Azure SQL Server LEFT CHARINDEXTSQL Azure SQL Server 左字符索引
【发布时间】:2015-10-07 22:10:25
【问题描述】:

我有一个 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"

这一直运作得相当好,直到今天我们注意到如果该人以所有大写字母输入地址,则会出现误报,如下所示:

我的使用理解:

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

在用于我的 JOIN 的空间之前会导致最左边的字符,但上图显示不应该发生的匹配?请帮助 SQL 初学者...

【问题讨论】:

    标签: c# sql-server tsql azure


    【解决方案1】:

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

    【讨论】:

    • 我很感谢您的回复,但我不确定答案是否告诉我查询没有到达服务器。究竟是什么让你做出这样的决定?谢谢布赖恩,我会尝试断点。
    • 我不认为服务器正在执行您与我们共享的查询,因为您似乎使用该代码构建的字符串与您的结果完全不匹配。我不认为这是您想要的查询或数据中字符串的情况的问题......我认为这是将正确字符串发送到服务器的后勤问题。对于您在问题中分享的信息,我无法为您提供帮助。这不仅仅是不恰当地匹配地址......它也忽略了连接 ID 的部分。
    • 问题是它已经运行了好几个月。这周才变得很奇怪,只有地址全部大写。也就是说,可以理解的是,由于信息有限,不太可能获得直接答案。我希望 CHARINDEX 和全部大写的线索可能会为某人敲响警钟,但它可能是一个红鲱鱼。此外,即使在我开发 SQL 语句时它是串联的,它在 VS 2015 中也是单行并且两个结果都匹配。但最重要的是您建议添加我目前正在阐明的断点。泰布赖恩!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    相关资源
    最近更新 更多