Solved

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

Posted on 2014-03-15
6
399 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 

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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Master DB with Masterkey 1 34
Adding items to a C# list incrementally 5 30
What is this datetime? 1 19
Can Angular be used with classic asp.net? 3 13
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…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

856 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