Home Forums SQL Server 2005 T-SQL (SS2K5) Help with sql statement to delete old records for user if multiple records found RE: Help with sql statement to delete old records for user if multiple records found

  • Here's two other ways of doing it. First, write a query returning the rows you want to keep:

    -- Query 1

    select *

    from #UserSession us

    where us.LastUpdated =(

    select Max( LastUpdated )

    from #UserSession

    where UserName = us.UserName );

    -- Query 2

    select us.*

    from #UserSession us

    left join #UserSession us2

    on us2.UserName = us.Username

    and us2.LastUpdated > us.LastUpdated

    where us2.UserName is null;

    For those leery of subqueries, Query 1 will be impressively fast if the table is large, assuming Username and LastUpdated are properly indexed.

    To delete, just invert the filter criteria and add to a DELETE statement. In this case, Query 2 is easier to invert so:

    delete

    from #UserSession us

    from #UserSession us

    left join #UserSession us2

    on us2.UserName = us.Username

    and us2.LastUpdated > us.LastUpdated

    where us2.UserName is not null;

    -- Verify

    select *

    from #UserSession;

    Will this be faster than using analytics? Probably not. But it never hurts to have alternate ways to get to where you want to go.

    Note: this code is written in SybaseIQ, which is the only system I have available to me at the moment. Some slight modification will be needed for Sql Server.

    TommCatt
    In theory, there is no difference between theory and practice. In practice, there is.