[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

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

Posted on 2014-03-15
6
Medium Priority
?
412 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 2000 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 41

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
Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

 

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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

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.
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

649 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