Solved

Comma separated IDs to get batch of records through Stored Procedure problems.

Posted on 2014-03-15
6
391 Views
Last Modified: 2014-03-16
Hello, I wan't to only select the newest record for an ID in the comma separed ID string:
ALTER PROCEDURE hhh_qqq.GetBatch
-- Add the parameters for the stored procedure here
@FriendListID VARCHAR(8000)
AS
BEGIN
    SELECT ID, latitude, longitude FROM Locations
    WHERE ID IN (SELECT * FROM SplitDelimiterString(@FriendListID, ','))
END

Open in new window

the used function called SplitDelimiterString:
CREATE FUNCTION SplitDelimiterString (@StringWithDelimiter VARCHAR(8000), @Delimiter VARCHAR(8))

RETURNS @ItemTable TABLE (Item VARCHAR(8000))

AS
BEGIN
    DECLARE @StartingPosition INT;
    DECLARE @ItemInString VARCHAR(8000);

    SELECT @StartingPosition = 1;
    --Return if string is null or empty
    IF LEN(@StringWithDelimiter) = 0 OR @StringWithDelimiter IS NULL RETURN; 
    
    WHILE @StartingPosition > 0
    BEGIN
        --Get starting index of delimiter .. If string
        --doesn't contain any delimiter than it will returl 0 
        SET @StartingPosition = CHARINDEX(@Delimiter,@StringWithDelimiter); 
        
        --Get item from string        
        IF @StartingPosition > 0                
            SET @ItemInString = SUBSTRING(@StringWithDelimiter,0,@StartingPosition)
        ELSE
            SET @ItemInString = @StringWithDelimiter;
        --If item isn't empty than add to return table    
        IF( LEN(@ItemInString) > 0)
            INSERT INTO @ItemTable(Item) VALUES (@ItemInString);            
        
        --Remove inserted item from string
        SET @StringWithDelimiter = SUBSTRING(@StringWithDelimiter,@StartingPosition + 
                     LEN(@Delimiter),LEN(@StringWithDelimiter) - @StartingPosition)
        
        --Break loop if string is empty
        IF LEN(@StringWithDelimiter) = 0 BREAK;
    END
     
    RETURN
END

Open in new window

The problem is that there is more records for each ID, I want to only select the newest record for the current ID.
My table has a column named Created that has a datetime when it is created.
0
Comment
Question by:JoachimPetersen
6 Comments
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 500 total points
ID: 39931809
Something like this perhaps:
;WITH    LocationsCTE
          AS (SELECT    l.ID,
                        l.latitude,
                        l.longitude,
                        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Created DESC) Row
              FROM      Locations l
                        INNER JOIN SplitDelimiterString(@FriendListID, ',') s ON l.ID = s.Item
             )
    SELECT  ID,
            latitude,
            longitude
    FROM    LocationsCTE
    WHERE   Row = 1

Open in new window

0
 

Author Comment

by:JoachimPetersen
ID: 39931826
When I try your procedure, I get no result, I wrote some sample names for the fields, here is the procedure I tested and got no result from my database.
ALTER PROCEDURE xxxxxx
-- Add the parameters for the stored procedure here
@FriendListID VARCHAR(8000)
AS
BEGIN
    WITH    LocationsCTE
          AS (SELECT    l.FaceID,
                        l.CurrentLatitude,
                        l.CurrentLongitude,
                        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Created DESC) Row
              FROM      Test_Locations l
                        INNER JOIN SplitDelimiterString(@FriendListID, ',') s ON l.CurrentLongitude = s.Item
             )
    SELECT  FaceID,
            CurrentLatitude,
            CurrentLongitude
    FROM    LocationsCTE
    WHERE   Row = 1
	
END

Open in new window

my table (Test_Locations) is this:
ID (identifyer for the table - not going to be used for anything)
FaceID (bigint - used to refere to the user that the data apply to)
CurrentLatitude (float - shows lat)
CurrentLongitude (float - shows long)
Created (datetime - shows when row was created)

Open in new window

0
 
LVL 40

Expert Comment

by:Sharath
ID: 39932184
try this.
ALTER PROCEDURE hhh_qqq.GetBatch
-- Add the parameters for the stored procedure here
@FriendListID VARCHAR(8000)
AS
BEGIN
    SELECT ID, latitude, longitude FROM Locations
    WHERE ID IN (SELECT MAX(Item) FROM SplitDelimiterString(@FriendListID, ','))
END

Open in new window


If you still not getting what you are looking for, post some sample data with expected result.
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

Author Comment

by:JoachimPetersen
ID: 39932296
Okay, what I want is to select different IDs entries that I pass to the stored procedure, this works and all, but when I have 8 or 1000 refering to the same ID, I want only to SELECT the row where there field Created has the newest data for all the rows with that ID, here is an example:

I input 11,22 to the stored procedure (FriendListID), and I would get a result like this.
ID:11 - Created:5/4/2007 1:34:11 AM
ID:11 - Created:5/4/2007 1:31:11 AM
ID:11 - Created:5/4/2007 1:37:11 AM
ID:22 - Created:5/4/2007 1:34:33 AM
I want to get a result like this:
ID:11 - Created:5/4/2007 1:37:11 AM
ID:22 - Created:5/4/2007 1:34:33 AM
I want to only get the row with the ID:11 once, but I want to get the one that has the newest date in the field Created.
0
 
LVL 38

Expert Comment

by:Jim P.
ID: 39932571
I'm not quite sure where to add this in:

But if you use the Row_Number function:
ROW_NUMBER ( ) 
    OVER (  PARTITION BY ID, ORDER BY Created Desc ) AS Row_Num

Open in new window

It will give you the option to add in a WHERE Row_Num = 1 and that will get you the single records you need.
0
 

Author Closing Comment

by:JoachimPetersen
ID: 39932600
Was the correct solution, just me that had a little issue with my database not updating my stored procedure.
0

Featured Post

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now