Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Order by user defined table type

Author  Topic 

AbeHoffman
Starting Member

2 Posts

Posted - 2014-12-12 : 17:13:41
Hello,

I'm a bit new sql dev, but I can't seem to find the best way to ask this. My question is similar to:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=196462

But varies just enough to be annoying. I've got a user defined table type called StringDictionaryTVP:

CREATE TYPE [dbo].[StringDictionaryTVP] AS TABLE(
[key] [varchar](500) NULL,
[value] [varchar](500) NULL
)

Ideally I would like to be able to have a # of columns and directions in this table like so:

DECLARE @OrderByClause StringDictionaryTVP

INSERT INTO @OrderByClause([key], [value])
values('gender','desc')
INSERT INTO @OrderByClause([key], [value])
values('name','asc')

Since our database can be a bit sizable, I'd also like to use Common Table Expressions so I can page through them fairly easy.

So my standard cte is something like this:
---
DECLARE @PageIndex INT = 0
DECLARE @PageSize INT = 20

;WITH results_cte AS ( SELECT U.*, ROW_NUMBER() over ( ORDER BY name ) RowNum
from Users U)

SELECT * FROM results_cte
WHERE RowNum > @Offset AND RowNum <= @Offset + @PageSize
--

So where 'ORDER BY name' is I'd like to use the @OrderByClause in some sort of dynamic way. I've tried all kinds of stuff but even something like this doesn't get the actual column name I need

;WITH results_cte AS ( SELECT U.*, ROW_NUMBER() over ( ORDER BY (select top 1 [key] +' '+ [value] from @OrderByClause) ) RowNum
from Users U)

===

I may be chasing the wrong stick, but outside of dynamic sql, is something like this possible?

Thanks,

Abe

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2014-12-13 : 09:08:33
See this article on catch-all queries: http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/

But I think you'll need to use dynamic sql to get the effect you want.
Go to Top of Page

AbeHoffman
Starting Member

2 Posts

Posted - 2014-12-14 : 19:21:39
quote:
Originally posted by gbritton

See this article on catch-all queries: http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/

But I think you'll need to use dynamic sql to get the effect you want.



Great! I think that'll work!
Go to Top of Page
   

- Advertisement -