Solved

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

Posted on 2014-03-15
6
386 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:JoachimPetersen
Comment Utility
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.
Comment Utility
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
Comment Utility
Was the correct solution, just me that had a little issue with my database not updating my stored procedure.
0

Featured Post

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

PL/SQL can be a very powerful tool for working directly with database tables. Being able to loop will allow you to perform more complex operations, but can be a little tricky to write correctly. This article will provide examples of basic loops alon…
Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

762 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

10 Experts available now in Live!

Get 1:1 Help Now