Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

ORDER BY where the order is contained in a string

$
0
0

Hi

I have a web application that offers the user the ability to sort items on the page using jQuery Sortable. This is useful because the data being sorted cannot easily be sorted on some aspect of the data. It is up to the user to decide the sort order.

So, I have a list of newsletters that stores an order string for a list of related articles. It looks like this:

1,2,4,3,5

These are the article ID's and they (the stories/articles) are displayed by the jQuery code on the page in that order.

The problem is that I need to export the list of articles for a newsletter in that order using SQL.

So, these are the objects:

/* Newsletters holds the Order String [OrderString] for the stories in the next table */

CREATE TABLE [dbo].[DI_Newsletters](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](300) NOT NULL,
    [status] [int] NOT NULL,
    [OrderString] [varchar](300) NULL,  /* e.g. 2,4,3,6,8,7 */
    [Type] [int] NULL,
    [CreateDate] [datetime] NULL

)

CREATE TABLE [dbo].[DI_NewsLetterStories](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [NewsLetterID] [int] NOT NULL,
    [Title] [nvarchar](500) NOT NULL,
    [CreateDate] [datetime] NOT NULL,
    [LastModifiedDate] [datetime] NOT NULL,
    [Summary] [nvarchar](500) NULL,
    [FullText] [nvarchar](max) NULL,
    [Image] [varchar](300) NULL

)

/ * some test data */

insert into DI_Newsletters
(Name,status,OrderString,type,CreateDate
)
values
('Issue 1-2013',1,'2,1',0,GETDATE()
)

insert into DI_NewsLetterStories
(NewsLetterID,Title,CreateDate,
LastModifiedDate,Summary,FullText,[Image])
values
(1,'Story 1',Getdate(),getdate(),'test content1','','')

insert into DI_NewsLetterStories
(NewsLetterID,Title,CreateDate,
LastModifiedDate,Summary,FullText,[Image])
values
(1,'Story 2',Getdate(),getdate(),'test content2','','')

The problem is that I want to select all the Stories for a newsletter and order by the order string in the newsletters table in SQL.

Anyone got an idea how I might achieve something like:

select * from DI_NewsletterStories s

inner Join DI_NewsLetters nl on nl.newsletterId=s.newsletterId

where nl.newsletterID=1

order by nl.OrderString

nb: for the test data you would get two stories back and the one with the Id=2 would be first

thanks

Gus


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>