I have a rather long combinations of SQL statements to give me a 3 row result that I want to use in a Telerik Ticker. The Telerik Ticker as far as I can see will only accept Linq or Entity data sources.
So I have a Ticker with as DataSourceID = "LinqDataSource1" which has an OnSelecting Event.
My code behind has...
Protected Sub LinqDataSource1_Selecting(sender As Object, e As LinqDataSourceSelectEventArgs) Handles LinqDataSource1.Selecting
Dim db As New TestDataContext
Dim tickerquery As New StringBuilder
tickerquery.Append("DECLARE #ALL_Total int ")
tickerquery.Append("DECLARE #ABC_Total int ")
tickerquery.Append("DECLARE #XYZ_Total int ")
tickerquery.Append("DECLARE #ALL_TypeA int ")
tickerquery.Append("DECLARE #ABC_TypeA int ")
tickerquery.Append("DECLARE #XYZ_TypeA int ")
tickerquery.Append("DECLARE #ALL_TypeB int ")
tickerquery.Append("DECLARE #ABC_TypeB int ")
tickerquery.Append("DECLARE #XYZ_TypeB int ")
tickerquery.Append("DECLARE #ALL_TypeC int ")
tickerquery.Append("DECLARE #ABC_TypeC int ")
tickerquery.Append("DECLARE #XYZ_TypeC int ")
tickerquery.Append("DECLARE #ALL_TypeD int ")
tickerquery.Append("DECLARE #ABC_TypeD int ")
tickerquery.Append("DECLARE #XYZ_TypeD int ")
tickerquery.Append("DECLARE #ALL_TypeE int ")
tickerquery.Append("DECLARE #ABC_TypeE int ")
tickerquery.Append("DECLARE #XYZ_TypeE int ")
tickerquery.Append("DECLARE #ALL_Title nvarchar(3) ")
tickerquery.Append("DECLARE #ABC_Title nvarchar(3) ")
tickerquery.Append("DECLARE #XYZ_Title nvarchar(3) ")
tickerquery.Append("SET #ALL_Title = 'ALL' ")
tickerquery.Append("SET #ABC_Title = 'ABC' ")
tickerquery.Append("SET #XYZ_Title = 'XYZ' ")
tickerquery.Append("DECLARE #Count_Tbl table (Title nvarchar(3), Total int, TypeA int, TypeB int, TypeC int, TypeD int, TypeE int) ")
tickerquery.Append("SELECT #ALL_Total = (SELECT Count(ProdID) FROM Products) ")
tickerquery.Append("SELECT #ABC_Total = (SELECT Count(ProdID) FROM Products WHERE Category = 'ABC') ")
tickerquery.Append("SELECT #XYZ_Total = (SELECT Count(ProdID) FROM Products WHERE Category = 'XYZ') ")
tickerquery.Append("SELECT #ALL_TypeA = (SELECT Count(ProdID) FROM Products WHERE Productstatus = 'TypeA') ")
tickerquery.Append("SELECT #ABC_TypeA = (SELECT Count(ProdID) FROM Products WHERE Category = 'ABC' AND Productstatus = 'TypeA') ")
tickerquery.Append("SELECT #XYZ_TypeA = (SELECT Count(ProdID) FROM Products WHERE Category = 'XYZ' AND Productstatus = 'TypeA') ")
tickerquery.Append("SELECT #ALL_TypeB = (SELECT Count(ProdID) FROM Products WHERE Productstatus = 'TypeB') ")
tickerquery.Append("SELECT #ABC_TypeB = (SELECT Count(ProdID) FROM Products WHERE Category = 'ABC' AND Productstatus = 'TypeB') ")
tickerquery.Append("SELECT #XYZ_TypeB = (SELECT Count(ProdID) FROM Products WHERE Category = 'XYZ' AND Productstatus = 'TypeB') ")
tickerquery.Append("SELECT #ALL_TypeC = (SELECT Count(ProdID) FROM Products WHERE Productstatus = 'TypeC') ")
tickerquery.Append("SELECT #ABC_TypeC = (SELECT Count(ProdID) FROM Products WHERE Category = 'ABC' AND Productstatus = 'TypeC') ")
tickerquery.Append("SELECT #XYZ_TypeC = (SELECT Count(ProdID) FROM Products WHERE Category = 'XYZ' AND Productstatus = 'TypeC') ")
tickerquery.Append("SELECT #ALL_TypeD = (SELECT Count(ProdID) FROM Products WHERE Productstatus = 'TypeD') ")
tickerquery.Append("SELECT #ABC_TypeD = (SELECT Count(ProdID) FROM Products WHERE Category = 'ABC' AND Productstatus = 'TypeD') ")
tickerquery.Append("SELECT #XYZ_TypeD = (SELECT Count(ProdID) FROM Products WHERE Category = 'XYZ' AND Productstatus = 'TypeD') ")
tickerquery.Append("SELECT #ALL_TypeE = (SELECT Count(ProdID) FROM Products WHERE Productstatus <> 'TypeD') ")
tickerquery.Append("SELECT #ABC_TypeE = (SELECT Count(ProdID) FROM Products WHERE Category = 'ABC' AND Productstatus = 'TypeE') ")
tickerquery.Append("SELECT #XYZ_TypeE = (SELECT Count(ProdID) FROM Products WHERE Category = 'XYZ' AND Productstatus = 'TypeE') ")
tickerquery.Append("INSERT INTO #Count_Tbl (Title, Total, TypeA, TypeB, TypeC, TypeD, TypeE SELECT #ALL_Title, #ALL_Total, #ALL_TypeA, #ALL_TypeB, #ALL_TypeC, #ALL_Decomm, #ALL_Running ")
tickerquery.Append("INSERT INTO #Count_Tbl (Title, Total, TypeA, TypeB, TypeC, TypeD, TypeE SELECT #ABC_Title, #ABC_Total, #ABC_TypeA, #ABC_TypeB, #ABC_TypeC, #ABC_Decomm, #ABC_Running ")
tickerquery.Append("INSERT INTO #Count_Tbl (Title, Total, TypeA, TypeB, TypeC, TypeD, TypeE SELECT #XYZ_Title, #XYZ_Total, #XYZ_TypeA, #XYZ_TypeB, #XYZ_TypeC, #XYZ_Decomm, #XYZ_Running ")
tickerquery.Append("SELECT Title, Total, TypeA, TypeB, TypeC, TypeD, TypeE FROM #Count_Tbl")
Dim results As IEnumerable(Of ProductCount) = _
db.ExecuteQuery(Of ProductCount) _
(tickerquery.ToString)
e.Result = results
End Sub
The error I get is
Incorrect syntax near the keyword 'SELECT'.
Incorrect syntax near the keyword 'SELECT'.
Incorrect syntax near the keyword 'SELECT'. at the tickerquery.ToString line
Is there another way of getting the results so that they can be bound to a Ticker?
Fixed... in my conversion to a series of appends to a string builder I had deleted some closing brackets in the 3 insert statements.
I had
tickerquery.Append("INSERT INTO #Count_Tbl (Title, Total, TypeA, TypeB, TypeC, TypeD, TypeE SELECT #ABC_Title, #ABC_Total, #ABC_TypeA, #ABC_TypeB, #ABC_TypeC, #ABC_Decomm, #ABC_Running ")
and I should have had
tickerquery.Append("INSERT INTO #Count_Tbl (Title, Total, TypeA, TypeB, TypeC, TypeD, TypeE) SELECT #ABC_Title, #ABC_Total, #ABC_TypeA, #ABC_TypeB, #ABC_TypeC, #ABC_Decomm, #ABC_Running ")
Related
ALTER Procedure [dbo].[GetItemsTypesByProduct]
(
#ProductID INT
)
As
Begin
Select distinct iMap.ProductId, iTyp.Id ItemTypeId, iTyp.ItemType, iTyp.SortOrder
from itemMapping iMap
inner join items itm on itm.itemid = imap.itemid
inner join itemType iTyp on iTyp.id = itm.ItemTypeId
Where ProductId = #ProductID
UNION
Select distinct rMap.ProductId, iTyp.Id, iTyp.ItemType, iTyp.SortOrder
from ReaderMapping rMap
inner join itemType iTyp on iTyp.id = 25
Where ProductId = #ProductID
UNION
Select distinct aMap.ProductId, iTyp.Id, iTyp.ItemType, iTyp.SortOrder
from AssessmentMapping aMap
inner join itemType iTyp on iTyp.id = 24
Where ProductId = #ProductID
order by productid, iTyp.SortOrder
Select distinct aTyp.AssessmentTypeId, AssessmentTypeName, MappingLevel
from eds_quiz..AssessmentType aTyp
inner join eds_quiz..Assessments asm on (asm.AssessmentTypeId = aTyp.AssessmentTypeId)
inner join AssessmentMapping aMap on (aMap.AssessmentId = asm.AssessmentId)
Where ProductId = #ProductID
Select Id, TypeName from eds_edusmart..lessontype
Where Id NOT IN (1, 2, 4)
End
I have the below query once I run it, it's exceeded successfully without error, but when I run it inside a procedure, I got the single error.
CREATE OR REPLACE PROCEDURE ABLEA_NEW.AB_VATFILE
IS
fHandle UTL_FILE.FILE_TYPE;
err varchar2(200);
v_str VARCHAR2(4000);
CURSOR VAT1 IS
SELECT (SELECT cif_no
FROM nbfc_customer_m
WHERE customerid = a.bpid) ||
(SELECT EXTRACT_ACCT(HOST_ACCT_INFO, 'SUFFIX')
FROM LEA_AGREEMENT_GROUPGL_MAP A, FA_ACCTCATG_M B
WHERE EXTRACT_ACCT(A.HOST_ACCT_INFO, 'ACCTCATG') = B.ACCTCATG
AND B.GROUPID = 'FA'
AND A.ACTIVE_FLAG = 'Y'
and AGREEMENTID = a.caseid)
"Account No",lpad(a.caseid,6,0) Loan_No
,
(SELECT AGREEMENTNO
FROM lea_agreement_dtl
WHERE AGREEMENTID = a.caseid)
AGREEMENTNO
,
LPAD(A.productid,3,0) Scheme_ID,
(SELECT rpad(schemedesc,35,' ')
FROM lea_scheme_m
WHERE schemeid = a.productid)
SchemeDesc,
to_char(a.advicedate,'ddmmyyyy') advicedate,
it_conv(a.adviceamt) adviceamt,
rpad(a.chargeid,6,' ')chargeid,
(SELECT rpad(chargedesc,35,' ')
FROM nbfc_charges_m
WHERE chargeid = a.chargeid)
"Charge Description",
IT_CONV(a.chargeamt)chargeamt,
(SELECT
decode(count(1),0,'N','Y')
FROM nbfc_pmnt_dtl y
WHERE a.txnadviceid = y.txnadviceid
AND a.status = 'A'
AND y.status IS NULL
--and TRUNC(y.pmntdate) between :p_datefrom and :p_dateto
AND a.tax_applicable = 'Y'
AND a.ptxnadviceid IS NULL)Paid,
LPAD(b.chargeid,6,0)
"VAT ChargeID",
(SELECT RPAD(chargedesc,35,' ')
FROM nbfc_charges_m
WHERE chargeid = b.chargeid)
"VAT Charge Description",
IT_CONV(b.chargeamt)
"VAT Amount"
FROM (SELECT *
FROM nbfc_txn_advice_dtl
WHERE status = 'A' AND tax_applicable = 'Y' AND ptxnadviceid IS NULL)
a,
(SELECT *
FROM nbfc_txn_advice_dtl
WHERE status = 'A' AND ptxnadviceid IS NOT NULL) b
WHERE a.txnadviceid = b.ptxnadviceid;
BEGIN
fHandle := UTL_FILE.FOPEN('UAEDB', 'VAT', 'W');
FOR I IN VAT1
LOOP
v_str:= null;
v_str:= I."Account No"||I.Loan_No||I.AGREEMENTNO || I.Scheme_ID ||I.SchemeDesc|| I.advicedate|| I.adviceamt|| I.chargeid||I."Charge Description"||I.chargeamt||I.Paid||
I."VAT ChargeID" ||I."VAT Charge Description"||I."VAT Amount";
UTL_FILE.PUTF(fHandle,v_str);
UTL_FILE.PUTF(fHandle, '\n');
END LOOP;
UTL_FILE.FCLOSE(fHandle);
END ;
/
How can I solve this?
Note: the query return mor than 10000 record.
comment or un-comment the "(select from )as ColumnAlias" query column one by one, you can find which sub query column return more than one row
I'm trying to do a select and I get an ORA-06533 subcript beyond count.
I don't understand why is this error because there are no subscripts in the select.
I post the relevant code:
TYPE Item IS RECORD (
entity number,
period number,
value NUMBER);
TYPE ItemSet IS TABLE OF Item;
modelo_pd ItemSet;
select id_scenario into sid from sae_lc_scen_var where us_type = num and type = 0 and id_segment = pid;
str := 'select distinct bd.entity_id, v.period_id, v.number_attribute_46 pd_pit
from sae_scenario s, sae_baseline b, sae_baseline_data bd, sae_entity e, v_sae_scenario_data v
where s.id = ' || sid || ' and b.scenario_type = s.scenario_type and b.id = bd.baseline_id
and bd.entity_id = e.id and b.id = s.baseline_id and v.scenario_id = s.id and v.baseline_id = b.id
and e.string_attribute_1 = ''' || t.name || ''' and v.e_string_attribute_1 = e.string_attribute_1';
execute immediate str bulk collect into modelo_pd;
The parameters for the query are from two other queries:
select id_scenario into sid from sae_lc_scen_var where us_type = num and type = 0 and id_segment = pid;
and the loop:
for t in (select v.id_segment, s.name, v.value expert, v.value3 selection, v.value2 correction from sae_lc_scen_var v, sae_lc_segments s
where v.us_type = 1 and v.type = 0
and s.id = v.id_segment and v.value <> 0)
The error raises in the dynamic select. That is in execute immediate str bulk collect into modelo_pd;
Any clue?
The full thing:
num := get_constant('US_TYPE_EAD_AGGREGATE');
for t in (select v.id_segment, s.name, v.value expert, v.value3 selection, v.value2 correction from sae_lc_scen_var v, sae_lc_segments s
where v.us_type = 1 and v.type = 0
and s.id = v.id_segment and v.value <> 0)
loop
-- value3: 0=Model, 1=Proxy VMG, 2=Expert, 3=PD_TTC
num := get_constant('US_TYPE_LGD_CALC_METHOD');
if t.selection = 0 then
num := get_constant('US_TYPE_MODELOS_PD');
select id_scenario into sid from sae_lc_scen_var where us_type = num and type = 0 and id_segment = pid;
str := 'select distinct bd.entity_id, v.period_id, v.number_attribute_46 pd_pit
from sae_scenario s, sae_baseline b, sae_baseline_data bd, sae_entity e, v_sae_scenario_data v
where s.id = ' || sid || ' and b.scenario_type = s.scenario_type and b.id = bd.baseline_id
and bd.entity_id = e.id and b.id = s.baseline_id and v.scenario_id = s.id and v.baseline_id = b.id
and e.string_attribute_1 = ''' || t.name || ''' and v.e_string_attribute_1 = e.string_attribute_1';
execute immediate str bulk collect into modelo_pd;
I've found the source of the error.
There is no rows for that select so when I use modelo_pd it gives that error.
What is unclear for me is why it is giving the line number way before the subscript is used.
I have column name in the table:
select LASTNAME
FROM dbo.Employees
WHERE LASTNAME = 'Smith'
and output of the above query is
LASTNAME
Smith
I want output like
LASTNAME
S
m
i
t
h
With a little help of a numbers table.
SQL Server:
select substring(E.LASTNAME, N.N, 1) as LASTNAME
from Employees as E
inner join Numbers as N
on N.N between 1 and len(E.LASTNAME)
order by E.LASTNAME, N.N
Oracle:
select substr(E.LASTNAME, N.N, 1) as LASTNAME
from Employees E
inner join Numbers N
on N.N between 1 and length(E.LASTNAME)
order by E.LASTNAME, N.N;
SQL Fiddle
In SQL Server, if you don't have a table of numbers, then you can use CTE to generate the list:
;with cte (id, start, numb) as
(
select id, 1 start, len(lastname) numb
from employees
union all
select id, start + 1, numb
from cte
where start < numb
)
select c.id, substring(e.lastname, c.start, 1)
from employees e
inner join cte c
on c.start between 1 and len(e.lastname)
and c.id = e.id
order by e.id, e.lastname;
See SQL Fiddle With Demo
----- function for splitting
CREATE FUNCTION [dbo].[SPLIT_Test] (
#string VARCHAR(8000) )
RETURNS #table TABLE (strval VARCHAR(8000))
AS
BEGIN
IF LEN(#string)>=1
BEGIN
DECLARE #fulllen int=LEN(#string),#lastlen int=0
WHILE #fulllen>#lastlen
BEGIN
INSERT INTO #table
SELECT SUBSTRING(#string,1,1)
SET #string= RIGHT(#String, LEN(#String) - 1)
SET #lastlen=#lastlen+1
END
RETURN
END
RETURN
END
---- query
GO
DECLARE #name table(name varchar(500),row int IDENTITY(1,1))
INSERT INTO #name
select LASTNAME
FROM dbo.Employees
WHERE LASTNAME = 'Smith'
DECLARE #Finalname table(name varchar(50))
DECLARE #startrow int =(SELECT MAX(row) FROM #name)
,#endrow int =1
WHILE #startrow>=#endrow
BEGIN
INSERT INTO #Finalname
Select strval from [dbo].[SPLIT_test] ((SELECT name FROM #name where row=#endrow)) WHERE strval<>''-- removing empty spaces
SET #endrow=#endrow+1
END
SELECT * FROM #Finalname
Is there a way to override default MVC3 WebGrid sorting behavior to call my controller (which will perform server side sorting and return the data) when sort is called?
Thanks for any help!
You can pass the server side sorted data to the webgrid, along with the info on how many records there are. http://msdn.microsoft.com/en-us/magazine/hh288075.aspx has a helpful walkthrough. I'm doing database level sorting/filtering/paging to minimize the amount of data being passed around. I don't think my webserver would love me if I passed all 70,000 objects a customer has just so they can see the 25 on page 1. This is pretty much everything you need, except the very lightweight view model that just wraps your IEnumerable collection with some extra paging data.
Since web grid just uses the query string vars to decide what to do you need to use a get method form. And you need to include the sort field/direction in querystring in a way webgrid knows how to read it. So you end up with urls like localhost/example/admin/thing?thingName=Hyatt&City=&State=TX&Country=&sort=city&sortdir=ASC
Controller:
public ActionResult Index(string thingName, string city, string state, string country, int page = 1)
{
const int pageSize = 25;
int totalRecords = 0;
IEnumerable<Thing> things = ThingModel.GetPagedSortedLocationsForCustomer(customerId, sort, sortdir, out totalRecords, pageSize, page, thingName, city, state, country);
PagedThings viewModel = new PagedThings(pageSize, page, totalRecords, things);
return View(viewModel);
}
View:
#model ExampleCompany.Area.ViewModels.PagedThings
#{
using (Html.BeginForm("Index", "ThingaMaBob", System.Web.Mvc.FormMethod.Get))
{
<label for="ThingName">ThingName</label>#Html.TextBox("ThingName", "")
<label for="City">City</label>#Html.TextBox("City", "")
<label for="State">State</label>#Html.TextBox("State", "")
<label for="Country">Country</label>#Html.TextBox("Country", "")
<input type="submit" value="Filter" />
<br />
var grid = new WebGrid(canPage: true, rowsPerPage: Model.PageSize, canSort: true);
grid.Bind(Model.Things, rowCount: Model.TotalRows, autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(htmlAttributes: new { id = "grid"},
columns: grid.Columns(
//ommitted
grid.Column("thingName", "Thing"),
));
Html.Hidden(grid.SortFieldName, grid.SortColumn);
Html.Hidden(grid.SortDirectionFieldName, grid.SortDirection == SortDirection.Ascending ? "ASC" : "DESC");
}
Model:
public static IEnumerable<Thing> GetPagedSortedThingsForCustomer(int customerid, String sortby, String sorttype, out int totalRecords, int pageSize, int pageIndex, string thingName, string city, string state, string country)
{
var tmp = new List<Thing>();
int total = 0;
dynamic dr = OurDBUtility.ReturnDR("ExampleProc_GetThingsSortedPaged", ConnectionInfo.ExampleConnection, customerid, sortby, sorttype, pageSize, pageIndex, thingName, city, state, country);
{
while (dr.Read())
{
var tmpThing = new Thing();
tmpThing.LoadFromDr(dr);
tmp.Add(tmpThing);
if (total == 0)
{
total = (int)dr["TOTAL_THINGS"];
}
}
}
totalRecords = total;
return tmp;
}
Proc with dynamic sql - yes, you could use Linq-to-Sql or other techniques if you wanted to, but i'm old school:
CREATE PROCEDURE ExampleProc_GetThingsSortedPaged
( #CustomerId int
, #sortby nvarchar(60)
, #sorttype nvarchar(60)
, #pageSize int
, #pageIndex int
, #thingName nvarchar(255) = null
, #city nvarchar(30) = null
, #state nvarchar(30) = null
, #country char(2) = null
)
as
DECLARE #strSql nvarchar(3000)
--calculate paging rows
declare #startRow int, #endRow int
--e.g. if you have a page size of 10, page 1 = 1 - 10, page 2 = 11 -20
set #startRow = ((#pageIndex - 1) * #pageSize) + 1
set #endRow = #startRow + #pageSize - 1
if #thingName = ''
set #thingName = null
if #city = ''
set #city = null
if #state = ''
set #state = null
if #country = ''
set #country = null
--return total for webgrid, accounting for filter
declare #totalThings int
select #totalThings = COUNT(*)
from EXAMPLE_TABLE T with(nolock)
where CUSTOMER_ID = #CustomerId
AND (T.THING_NAME LIKE #thingName + '%' OR #thingName is null)
AND (T.CITY LIKE #city + '%' or #city is null)
AND (T.STATE LIKE #state + '%' or #state is null)
AND (T.COUNTRY = #country or #country is null)
DECLARE #ParameterDefinition AS NVARCHAR(200)
set #ParameterDefinition = '#totalThings int, #CustomerId INT, #startRow INT, #endRow INT, #thingName nvarchar(255), #city nvarchar(30), #state nvarchar(30), #country char(2)'
--When we need to do dynamic sql it is better to use paramterization, but you cannot do (ORDER BY #sortBy).
SET #strSql = N'SELECT * from
(
select ROW_NUMBER() OVER (ORDER BY T.' + #sortby + ' ' + #sorttype + ') as Row,
#totalThings [TOTAL_THINGS],
T.THING_ID, T.THING_NAME, T.ADDRESS, T.CITY, T.STATE,
T.ZIP_CODE, T.COUNTRY
FROM EXAMPLE_TABLE T
WHERE T.CUSTOMER_ID = #CustomerId
AND (T.THING_NAME LIKE #thingName + ''%'' OR #thingName is null)
AND (T.CITY LIKE #city + ''%'' or #city is null)
AND (T.STATE LIKE #state + ''%'' or #state is null)
AND (T.COUNTRY = #country or #country is null)
) paged
where Row between #startRow and #endRow
ORDER BY Row'
--print #strSql
EXECUTE sp_executesql #strSql, #ParameterDefinition, #totalThings, #CustomerId, #startRow, #endRow, #thingName, #city, #state, #country
GO
Proc with CTE:
CREATE PROCEDURE ExampleProc_GetThingsSortedPaged
( #CustomerID int
, #sortby nvarchar(60)
, #sorttype nvarchar(60)
, #pageSize int = 25
, #pageIndex int = 1
, #thingName nvarchar(255) = null
, #city varchar(30) = null
, #state nvarchar(30) = null
, #country char(2) = null
)
as
declare #startRow int
declare #endRow int
SET #startRow = ((#pageIndex - 1) * #pageSize) + 1;
SET #endRow = #startRow + #pageSize - 1;
set #sortby = replace(LOWER(#sortby), '_', '')
SET #sorttype = LOWER(#sorttype)
if #sorttype != 'asc' and #sorttype != 'desc'
begin
set #sorttype = 'asc'
end
;with cte_things as (
SELECT
CASE
WHEN #sortby ='country' AND #sorttype = 'asc' then row_number() over (order by C.COUNTRY_NAME ASC)
WHEN #sortby ='country' AND #sorttype = 'desc' then row_number() over (order by C.COUNTRY_NAME DESC)
WHEN #sortby ='state' AND #sorttype = 'asc' then row_number() over (order by STATE ASC)
WHEN #sortby ='state' AND #sorttype = 'desc' then row_number() over (order by STATE DESC)
WHEN #sortby ='city' AND #sorttype = 'asc' then row_number() over (order by CITY ASC)
WHEN #sortby ='city' AND #sorttype = 'desc' then row_number() over (order by CITY DESC)
WHEN #sortby ='thingname' AND #sorttype = 'desc' then row_number() over (order by THING_NAME DESC)
ELSE row_number() over (order by THING_NAME ASC)
END AS Row
,T.THING_ID, T.THING_NAME, T.THING_TYPE, T.ADDRESS, T.CITY, T.STATE
, T.ZIP_CODE, T.COUNTRY_CODE, C.COUNTRY_NAME, T.PHONE_NUMBER
, T.LATITUDE, T.LONGITUDE
FROM EXAMPLE_TABLE L
join COUNTRIES C
on C.COUNTRY_CODE = L.COUNTRY_CODE
where
T.CUSTOMER_ID = #CustomerId
and L.CITY = ISNULL(#city, CITY)
and L.STATE = ISNULL(#state, STATE)
and L.COUNTRY_CODE = ISNULL(#country, L.COUNTRY_CODE)
and L.THING_NAME = ISNULL(#thingName, THING_NAME)
)
, cte_total as (select COUNT(*) as TOTAL_THINGS from cte_things)
, cte_all as (select cte_things.*, cte_total.TOTAL_THINGS from cte_things cross join cte_total)
SELECT * FROM cte_all
where
Row >= #startRow
and Row <= #endRow
ORDER BY Row
GO