SQL: Using three SELECT statements in a single query

Viewed 38

I have this query in a store procedure which works perfectly :

select  dbo.fn_GetSid(@Cid,sid) as SIdPrfx, 
        dbo.fn_GetPId(@Cid, sid, pid) as PIdPrefix,
        *
from    #tempsafety 
where   (createddate >= @dateFrom or @dateFrom is null) and 
        (createddate<= @dateTo or @dateTo is null) 
order by createddate desc

But I want to change the order and put the SIdPrfx and PIdPrefix in the end of the select output

2 Answers

We can simply do this:

SELECT  
    *,
    dbo.fn_GetSid(@Cid,sid) as SIdPrfx, 
    dbo.fn_GetPId(@Cid, sid, pid) as PIdPrefix
FROM #tempsafety
-- -- --

You might be able to get them into the last spot with an outer apply:

select  *
from    #tempsafety 
outer apply
        (
        select  dbo.fn_GetSid(@Cid,sid) as SIdPrfx, 
                dbo.fn_GetPId(@Cid, sid, pid) as PIdPrefix
        ) sub
where   (createddate >= @dateFrom or @dateFrom is null) and 
        (createddate<= @dateTo or @dateTo is null) 
order by createddate desc
Related