Click here to Skip to main content
15,899,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I use a table-valued function as a parametered view. Almost everything works, except the order by part.I altered the original function into this short one.

The function:

ALTER FUNCTION [dbo].[fn_Get_NormalOrders]
(	
	@minimalLevel int,
	@recordStart int,
	@recordsEnd int,
	@orderBy varchar(30)
)
RETURNS TABLE 
AS
RETURN 
(
	select * 
		from
		(
			select 
				ROW_NUMBER() over (order by @orderBy) as row
				,d.nameModel
				,t.idToner
			from toner t
				inner join vwWebDevice d on d.idDevice = t.idDevice 
					and d.statusDevice not like '%stale%'
					and isnull(d.deleted,0) = 0
				inner join groups g on g.idGroup = d.idGroup

			where 
				t.currentLevel <= @minimalLevel

		) as x
	where x.row between @recordStart and @recordsEnd
)


What I have tried:

I found a solution by making a varchar of this query and execute this, but how do i return te result? When i use it as it is now, than the result is always the same.
Posted
Updated 12-Apr-17 2:08am
v3
Comments
CHill60 12-Apr-17 7:26am    
It's my understanding that you cannot execute dynamic sql from inside a function. What are you actually trying to achieve?

1 solution

I want to sort the result by column via a PHP webportal. At first i had a heavy query in the script (i made it very short for this topic), but i wanted to put the heavy logic on the SQL server. Something like a view with lots of logic in it. I got everything in except the table sort (and also the very important paging).

I found the solution ( with a little bit of help :-) ). Instead of convert the query to text, than alter the sting and than excute it, i used a case. I had to add a extra sort afterwards because the result was not sorted on the row.

I can now use the function like:
select * from dbo.fn_Get_NormalOrders(40,5,30,'nameModel') order by row


select *
    from
    (
        select
            case @orderBy
                when 'nameModel' then ROW_NUMBER() over (order by d.nameModel)
                when 'idToner' then ROW_NUMBER() over (order by t.idToner)
                else ROW_NUMBER() over (order by t.DTE)
            end as [row]
            ,d.nameModel
            ,t.idToner
        from toner t
            inner join vwWebDevice d on d.idDevice = t.idDevice
                and d.statusDevice not like '%stale%'
                and isnull(d.deleted,0) = 0
            inner join groups g on g.idGroup = d.idGroup

        where
            t.currentLevel <= 20

    ) as x
where x.row between 1 and 20
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900