SQL Pagination With Dynamic Order By

Apr 4, 2007

I have a need to perform pagination while using dynamic sorting. As
an exmaple -

SELECT TOP(10) * FROM (
SELECT
TextColumn,
DecimalColumn,
ROW_NUMER() OVER (
ORDER BY
CASE @x
WHEN 1 THEN TextColumn
WHEN 2 THEN DecimalColumn
END
DESC
) AS SortOrder
FROM Table1
) AS Results WHERE SortOrder ( 10 ) ORDER BY SortOrder

This is obviously just some sample but an error is given because the
data type of the 2 columns used in the order by are different. It
works if I cast DecimalColumn to match the textcolumn but then the
sorting is wrong. Is there a way to do this in a single query with 2
different data types?

Thanks for your help.

View 2 Replies


ADVERTISEMENT

Using Dynamic Order By

Jun 23, 2005

declare @OrderBy as varchar(20) if(@DateType = 1) set @OrderBy = (select 'lastchange') --lastchange is a column name select * from xtableorder by [@OrderBy] ascI am getting an error saying that column name @OrderBy does not exist.How can I sort the search using the @OrderBy variable?Thanx

View 2 Replies View Related

Dynamic ORDER BY

Apr 29, 2008

Dear All,

I have a set of rows, a sample listed below

ID Status PageID
1 1 0
2 1 12
3 2 15
4 4 0
5 0 0
6 4 13
7 0 0
8 4 15
9 2 0

Now I wish to list the rows in Status ASC order, however, only those rows that have the Page ID > 0 will be ordered.

How can i achieve that?

I tried something like
ORDER BY CASE pageID > 0 THEN Status ASC

However I have a syntax error

Thanks for your help and time

Johann

View 3 Replies View Related

Dynamic Order By

Apr 14, 2007

I am using a dynamic order by statement;ORDER BY CASE @sortWHEN 0 THEN CAST( COALESCE( t2.RANK, 0 ) + COALESCE( t3.RANK,0 ) AS CHAR( 5 ) )WHEN 1 THEN C.titleWHEN 2 THEN CAST( CEILING( [dbo].[fn_calculateDistance]( @fromLatitude, @fromLongitude, L.latitude, L.longitude ) ) ASCHAR( 9 ) )WHEN 3 THEN ( C.locality + ' ' + C.state )WHEN 4 THEN CAST( C.price AS CHAR( 10 ) ) END ASCThe problem is with the numeric values, I have to cast them as astring, but in the results 114kmobviously is not between 1137km and 1144km.Anyone any ideas on this?Thanks in advance.

View 4 Replies View Related

Dynamic Order By And JOIN

Mar 29, 2005

Hi,

Here is my code:

ALTER PROCEDURE dbo.sp_GetPeopleDetails_1

@OrderByClause varchar(100)
AS
DECLARE @SQLStatement varchar(255)

SELECT @SQLStatement = 'SELECT  People.PeopleID, People.FirstLastName, People.Title,
           
           
Departments.AcademicArea, Shifts.ShiftName, People.TShirt,
           
            People.Parking
FROM Departments INNER JOIN
           
            People ON
Departments.DepartmentID = People.DepartmentID
           
            INNER JOIN
Shifts ON People.ShiftID = Shifts.ShiftID
           
            order By ' +
@OrderByClause   

EXEC(@SQLStatement)

/* SET NOCOUNT ON */
RETURN

When I run it, the error is: "Incorrect syntax near the keyword 'IN'."

Can anyone point my mistake?

Thanks.

View 4 Replies View Related

Distinct & Dynamic ORDER BY

Apr 29, 2008

Hello,

I have a stored procedure with dynamic ORDER BY. I would like to use the DISTINCT too. Is it somehow possible?
Thank you

Here is the stored procedure:

SELECT identifier_company + cast(identifier_number as nvarchar(3)) as identifier,
CASE WHEN canceled = 'True' THEN 'canceledPO' ELSE '' END AS style,
staff.staff_name,
purchase.purchase_id,
purchase.traveller_name,
nominal_department.department_name,
purchase.canceled,
purchase.travel_date,
convert(nvarchar(20), purchase.date_raised, 103) as dated,
supplier
FROM purchase INNER JOIN purchase_project ON purchase.purchase_id = purchase_project.purchase_id
INNER JOIN staff ON purchase.raised = staff.staff_id
INNER JOIN nominal_department ON purchase.department = nominal_department.nominal_dep_id
WHERE (raised in (SELECT staff_id FROM staff WHERE department like @FromDepartment) or purchase.raised = @raisedBy)
and purchase_project.project_number like '%' + @Query + '%'
ORDER BY
CASE @SortDir
WHEN 'ASC' THEN
CASE @OrderBy
WHEN 'staff_name' THEN cast(staff_name as nvarchar(100))
WHEN 'traveller_name' THEN cast(traveller_name as nvarchar(100))
WHEN 'department_name' THEN cast(department_name as nvarchar(100))
WHEN 'supplier' THEN cast(supplier as nvarchar(100))
WHEN 'canceled' THEN cast(canceled as nvarchar(10))
END
END
ASC,
CASE @SortDir
WHEN 'DESC' THEN
CASE @OrderBy
WHEN 'staff_name' THEN cast(staff_name as nvarchar(100))
WHEN 'traveller_name' THEN cast(traveller_name as nvarchar(100))
WHEN 'department_name' THEN cast(department_name as nvarchar(100))
WHEN 'supplier' THEN cast(supplier as nvarchar(100))
WHEN 'canceled' THEN cast(canceled as nvarchar(10))
END
END
DESC

View 3 Replies View Related

Dynamic ORDER BY And UNION

May 13, 2008

Hello,

I am trying to use dynamic ORDER BY with UNION in a stored procedure but I keep getting this error message:

ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

The ORDER BY works fine without the UNION, and the UNION works fine without the dynamic ORDER BY (just putting an ORDER BY works fine)

Here is the whole query in case this helps, thank you

SELECT
leave_id, leave_type, annualLeave.from_date,
convert(nvarchar(10), annualLeave.request_date, 103) as dated,
convert(nvarchar(10), annualLeave.from_date, 103) as from_date,
convert(nvarchar(10), annualLeave.to_date, 103) as to_date,
annualLeave.canceled,
annualLeave.working_days,
staff.staff_name,
Case WHEN annualLeave.canceled = 'True' THEN 'canceledPO'
WHEN annualLeave.authorized_mng is not NUll AND annualLeave.authorized_hr is not Null THEN 'greenItem'
ELSE ''
END AS pendingStyle,
Case WHEN annualLeave.canceled = 'True' THEN 'canceledPO'
ELSE ''
END AS historyStyle
FROM annualLeave
INNER JOIN staff ON annualLeave.staff = staff.staff_id
WHERE staff.department like @Department
and (@staffID is Null or annualLeave.staff = @StaffID)
and (@Canceled is Null or annualLeave.canceled = @Canceled)
and (@AuthorizedMng is Null or annualLeave.authorized_mng is Null)
and (@AuthorizedHR is Null or annualLeave.authorized_hr is Null)
and (@StartingDate is Null or annualLeave.from_date > @Startingdate)
and (@IsPastLeave is Null or annualLeave.from_date < @IsPastLeave)
and (@EndingDate is Null or annualLeave.to_date <= @EndingDate)

UNION

SELECT
leave_id, leave_type, annualLeave.from_date,
convert(nvarchar(10), annualLeave.request_date, 103) as dated,
convert(nvarchar(10), annualLeave.from_date, 103) as from_date,
convert(nvarchar(10), annualLeave.to_date, 103) as to_date,
annualLeave.canceled,
annualLeave.working_days,
staff.staff_name,
Case WHEN annualLeave.canceled = 'True' THEN 'canceledPO'
WHEN annualLeave.authorized_mng is not NUll AND annualLeave.authorized_hr is not Null THEN 'greenItem'
ELSE ''
END AS pendingStyle,
Case WHEN annualLeave.canceled = 'True' THEN 'canceledPO'
ELSE ''
END AS historyStyle
FROM annualLeave
INNER JOIN staff ON annualLeave.staff = staff.staff_id
WHERE staff.department like @Department
and (@staffID is Null or annualLeave.staff = @StaffID)
and (@Canceled is Null or annualLeave.canceled = @Canceled)
and (@AuthorizedMng is Null or annualLeave.authorized_mng is Null)
and (@AuthorizedHR is Null or annualLeave.authorized_hr is Null)
and annualLeave.leave_type like 'Leave in lieu'
ORDER BY
CASE @OrderDir
WHEN 'ASC' THENannualLeave.from_date
END
ASC,
CASE @OrderDir
WHEN 'DESC' THEN annualLeave.from_date
END
DESC

View 3 Replies View Related

Dynamic ORDER BY Within Stored Procedure

Jul 7, 2004

I am trying to do something similar to the following where I want to perform dynamic ordering on two tables that have been unioned as shown below.


CREATE PROCEDURE procedure_name
@regNum varchar(14),
@sortOrder tinyint = 1
AS
SELECT Filler_OrdNum As 'Accession', RTrim(Obs_Code) As 'Observation', REG As 'Register',
Obs_Date As 'Observation Date'
FROM tblSPG_Header
WHERE
REG = @regNum
UNION
SELECT Filler_OrdNum As 'Accession', RTrim(Obs_Code) As 'Observation', REG As 'Register',
Obs_Date As 'Observation Date'
FROM tblRCH_Header
WHERE
REG = @regNum
ORDER BY Obs_Date DESC
GO


Note that I am only sorting on the Obs_Date column, but I'd like to be able to sort on any column within the selection list. I know that I need to use:


ORDER BY CASE WHEN @sortOrder = 1 THEN Obs_Date END DESC


but I frequently get the following error when I try to do so:

"ORDER BY items must appear in the select list if the statements contain a UNION operator"

If anyone can offer any suggestions, I would appreciate it. Thanks.

View 1 Replies View Related

Dynamic Order By W/ Additional Parameters

Jan 16, 2006

I have a stored procedure that uses a dynamic order by statement.  This statement works okay until I try to select ticket's by userEmail which is passed in to my stored procedure as a parameter.  Here is the code that works for my dynamic sort order:
CREATE PROCEDURE [dbo].[SelectAllTickets]
@SortOrder varchar(250)
AS
SET NOCOUNT ON
Exec('SELECT a.TicketID, a.TicketDate, a.TicketName, a.TicketDescription, a.statusID, a.resolutionID, a.userID,
b.typeID, b.typeName,
c.userID, c.UserFirstName,
f.statusID, f.statusName
FROM Tickets a
LEFT OUTER JOIN Type b ON b.typeID = a.typeID
LEFT OUTER JOIN Users c ON c.userID = a.userID
LEFT OUTER JOIN Status f ON f.statusID = a.statusID
ORDER BY ' + @SortOrder)
I modied this procedure to create one in which I select tickets based on the userEmail as a criteria as well.. this one fails due to Incorrect syntax near the keyword 'BY'
CREATE PROCEDURE [dbo].[SelectTicketByUser]@SortOrder varchar(250),@userEmail varchar(50)
AS   SET NOCOUNT ON   Exec('SELECT a.TicketID, a.TicketDate, a.TicketName, a.TicketDescription, a.statusID, a.resolutionID, a.userID,  b.typeID, b.typeName,  c.userID, c.UserFirstName, c.userEmail,  f.statusID, f.statusName      FROM Tickets a  LEFT OUTER JOIN Type b ON b.typeID = a.typeID LEFT OUTER JOIN Users c ON c.userID = a.userID LEFT OUTER JOIN Status f ON f.statusID = a.statusID WHERE a.statusID <> 40 AND c.userEmail = ' + @userEmail + 'ORDER BY ' + @SortOrder)
Any ideas on what syntax I should be using? Thanks!

View 3 Replies View Related

Dynamic Order BY In Stored Procedure

Sep 28, 2012

I can't figure out why this won't work. I want to use a variable for the 'ORDER BY' in my Stored Procedure.

I use this to order my results by product price or alphabetically from a dropdown menu. I have tried the following, but get the error below.

Code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[SPResults]

[Code] ....

Code:
Msg 1008, Level 16, State 1, Procedure SPResults, Line 21

The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name. Is this possible to do?

View 3 Replies View Related

Dynamic ORDER BY In Stored Procedure

Apr 28, 2008

Hello,

I have this stored procedure:
SELECT * from purchase
ORDER BY
CASE @OrderBy
WHEN 'traveller_name' THEN cast(traveller_name as nvarchar(100))
WHEN 'canceled' THEN cast(canceled as bit)
END

the @OrderBy is a nvarchar(100) parameter
traveller_name is an nvarchar(100) field
canceled is a bit field


When I execute the stored procedure it works fine until I execute it sorting by canceled field. After that, I cannot sort it again using the traveller_name field. I get this eror:
Conversion failed when converting the nvarchar value 'Jason' to data type bit.
(Jason is a record in the traveller_name)
Removing the castings and sorting by just the column name does not help.

Any ideas?
Thank you

View 7 Replies View Related

UNION With Dynamic Order By Failing

Nov 30, 2007

Hi,
Can anyone help as to how to get this to work? dbo.parseInt is a Function which sorts Alpha Numerically. If I removed the top part of the UNION, the Procedure works fine.

ALTER PROCEDURE dbo.ByJobNoAlphaNumeric as
SELECT 0 AS JobID, '<All Jobs>' AS JobNo
UNION SELECT JobID, JobNo FROM tbl
ORDER BY dbo.parseInt(JobNo)

Regards
Andrew

View 2 Replies View Related

Dynamic Sql Where And Order By Clauses In Stored Procedure

Feb 17, 2008

Hi, I hope some one can help me. I have a stored procedure (Microsoft SQL 2005 Express Edition) that I want users to be able to dynamically set the, group by, order by (@orderby) and where clause (@where). I have managed to get the group by to work but can't seem to get the where and order by to work. Here's my stored procedure. Any idea how this can be done? ALTER PROCEDURE [dbo].[sp_aggregate]     -- Add the parameters for the stored procedure here @finfileid int,     @phaseid int, @supplierid int, @measurementid int, @roleid int, @groupby int, @orderby int, @where int AS BEGIN     -- SET NOCOUNT ON added to prevent extra result sets from     -- interfering with SELECT statements.     SET NOCOUNT ON;     -- Insert statements for procedure here     SELECT     MAX(ProjectFinFileMonthItems.ProjFinFileMonthItemsMonthId) AS ProjFinFileMonthItemsMonthId,                       SUM(ProjectFinFileMonthItems.ProjFinFileMonthItemsValue * ProjectFinFileMonthItems.ProjFinFileMonthItemsRate * ProjectFinFileMonthItems.ProjFinFileMonthItemsAvail                        / 100) AS total, MAX(ProjectFinFileItems.ProjPhaseId) AS phaseid, MAX(ProjectFinFileMonthItems.ProjDeliveId) AS deliveid, MAX(ProjectFinFileMonthItems.SupplierId)                       AS supplierid, MAX(ProjectFinFileMonthItems.ProjFinFileItemsId) AS ProjFinFileItemsId, MAX(ProjectFinFileMonthItems.ProjFinFileMonthItemsId)                       AS ProjFinFileMonthItemsId, MAX(ProjectFinFileMonthItems.ProjDeliveId) AS ProjDeliveId, MAX(ProjectPhases.ProjectPhaseName) AS ProjectPhaseName,                       MAX(Suppliers.SupplierName) AS SupplierName, MAX(ProjectFinFileMonthItems.RoleId) AS RoleId, MAX(Measurements.MeasurementName) AS MeasurementName,                       MAX(ProjectFinFileMonthItems.MeasurementId) AS MeasurementId, MAX(ProjectFinFileMonthItems.FinDataTypeId) AS FinDataTypeId,                       MAX(FinDataTypes.FinDataTypeName) AS FinDataTypeName, max(ProjectFinFileItems.FinFileId) as finfileid FROM         ProjectFinFileItems INNER JOIN                       ProjectFinFileMonthItems ON ProjectFinFileItems.ProjFinFileItemsId = ProjectFinFileMonthItems.ProjFinFileItemsId LEFT OUTER JOIN                       FinDataTypes ON ProjectFinFileMonthItems.FinDataTypeId = FinDataTypes.FinDataTypeId LEFT OUTER JOIN                       Measurements ON ProjectFinFileMonthItems.MeasurementId = Measurements.MeasurementId LEFT OUTER JOIN                       Roles ON ProjectFinFileMonthItems.RoleId = Roles.RoleId LEFT OUTER JOIN                       ProjectPhases ON ProjectFinFileItems.ProjPhaseId = ProjectPhases.ProjectPhaseId LEFT OUTER JOIN                       Suppliers ON ProjectFinFileMonthItems.SupplierId = Suppliers.SupplierId /*dynamic where clause needs to go here */ /*dynamic group by clause */ GROUP BY CASE when @groupby=1 then ProjectFinFileItems.projphaseid  --phaseid when @groupby=2 then ProjectFinFileMonthItems.supplierid -- supplierid when @groupby=3 then ProjectFinFileMonthItems.measurementid -- measurment when @groupby=4 then ProjectFinFileMonthItems.roleid --role else ProjectFinFileMonthItems.ProjFinFileMonthItemsId END /*dynamic order clause needs to go here */ END cheers Mark :)

View 2 Replies View Related

How To Pass Dynamic Parameter To Order BY Clause

Sep 13, 2004

Hi,

I use a DataGrid to show the data, and I want it has a sorting and Paging function,
so I use dataset to collect the data from middle tier function and stored procedure.
I have code in aspx page like BindData(ViewState("SortExpr")).

In the stored procedure I pass SortExpr as parameter as following:

CREATE Procedure Ruying_AutoSearch10
(
@Make varchar(50),
@Model varchar(50) = NULL,
@Condition varchar(20) = NULL,
@Miles float,
@Zipcode varchar(5),
@SortExpr varchar(100)
)
AS

DECLARE @RowCount int
SELECT @RowCount = Count(*) FROM ZIPCodes WHERE ZIPCode = @Zipcode AND CityType = 'D'

if @RowCount > 0
BEGIN
SELECT
z.ZIPCode, z.City, z.StateCode, a.Make, a.Model, a.AutoPrice, a.AutoPrice2, a.AutoYear, a.Mileage, a.AdID, a.ImageURL, dbo.DistanceAssistant(z.Latitude,z.Longitude,r.Latitude,r.Longitude) As Distance
/*
The above functions requires the Distance Assistant.
*/
FROM
ZIPCodes z, RadiusAssistant(@ZIPCode,@Miles) r, AutoAd a
WHERE
z.Latitude <= r.MaxLat
AND z.Latitude >= r.MinLat
AND z.Longitude <= r.MaxLong
AND z.Longitude >= r.MinLong
AND z.CityType = 'D'
AND z.ZIPCodeType <> 'M'
AND z.ZIPCode = a.Zipcode
AND a.AdActive = '1'
AND a.AdExpiredate >= getdate()
AND a.Make = @Make
AND a.Model = IsNull(@Model,a.Model)
AND a.Condition = IsNull(@Condition, a.Condition)
AND dbo.DistanceAssistant(z.Latitude,z.Longitude,r.Latitude,r.Longitude) <= @Miles
ORDER BY @SortExpr
END
ELSE
SELECT -1 As ZIPCode
--ZIP Code not found...
GO


but I got the error as "variables are only allowed when ordering by an expression referenceing
a column name". How I fix this error? Please help.

Thanks.

Lin

View 9 Replies View Related

Paging And Dynamic Sort Order (ASC/DESC)

Apr 14, 2007

Hi all,I have a SQL statement that allows paging and dynamic sorting of thecolumns, but what I can't figure out without making the SQL a dynamicstring and executing it, or duplicating the SQL statement between anIF and ELSE statement.Following is the SQL statement;set ANSI_NULLS ONset QUOTED_IDENTIFIER ONgoALTER PROCEDURE [dbo].[sp_search]@search VARCHAR( 80 ), @startRow INT = 1, @endRow INT = NULL, @postcode AS CHAR( 4 ) = NULL, @suburb AS VARCHAR( 40 ) = NULL, @stateIdentity AS TINYINT = NULL, @fromLatitude AS REAL = NULL -- latitude the user is located in, @fromLongitude AS REAL = NULL -- longitude the user is located in, @sort TINYINT = 1ASBEGINSET NOCOUNT ON;DECLARE @calculateDistance BIT;SET @calculateDistance = 0;-- get the longitude and latitude if requiredIF ( NOT @postcode IS NULL )BEGINSELECTDISTINCT@fromLatitude = latitude, @fromLongitude = longitudeFROMtbl_postalcodeWHERE(postalcode = @postcode)SET @calculateDistance = 1ENDELSE IF ( NOT @suburb IS NULL AND NOT @stateIdentity IS NULL )BEGINSELECTDISTINCT@fromLatitude = latitude, @fromLongitude = longitudeFROMtbl_localityWHERE(locality = @suburb)AND(stateIdentity = @stateIdentity)SET @calculateDistance = 1END/*ELSE IF ( @fromLatitude IS NULL AND @fromLongitude IS NULL )BEGINRAISERROR( 'You need to pass a valid combination to this storedprocedure, example: postcode or suburb and state identity or longitudeand latitude', 18, 1 );END*/SELECT D1.[row], D1.[totalRecordCount], D1.[classifiedIdentity], D1.[title], D1.[summary], D1.[price], D1.[locality], D1.[state], D1.[postcode], D1.[addedLast24], D1.[dateStamp], D1.[t2Rank], D1.[t3Rank], D1.[tRank], D1.[distance], F.[originalName], F.[extension], F.[uniqueName]FROM(-- derived tableSELECT ROW_NUMBER() OVER ( ORDER BY CASE @sort WHEN 0 THENCAST( COALESCE( t2.RANK, 0 ) + COALESCE( t3.RANK, 0 ) AS CHAR( 5 ) )WHEN 1 THEN C.title WHEN 2 THEN CAST( CEILING( [dbo].[fn_calculateDistance] ( @fromLatitude, @fromLongitude, L.latitude,L.longitude ) ) AS CHAR( 9 ) ) WHEN 3 THEN ( C.locality + ' ' +C.state ) WHEN 4 THEN CAST( C.price AS CHAR( 10 ) ) END ASC ) AS row, COUNT( * ) OVER() AS totalRecordCount, C.[classifiedIdentity], C.[title], C.[summary], C.[price], C.[locality], C.[state], C.[postcode], CASE WHEN ( C.[dateStamp] >= DATEADD( day, -1, GETDATE() ) )THEN 1 ELSE 0 END AS addedLast24, C.[dateStamp]/* , t1.RANK AS t1Rank */, t2.RANK AS t2Rank, t3.RANK AS t3Rank, /* COALESCE( t1.RANK, 0 ) + */ COALESCE( t2.RANK, 0 ) +COALESCE( t3.RANK, 0 ) AS tRank, CASE @calculateDistance WHEN 1 THEN CEILING( [dbo].[fn_calculateDistance] ( @fromLatitude, @fromLongitude, L.latitude,L.longitude ) ) ELSE 0 END AS distanceFROM [tbl_classified] AS CINNER JOINtbl_locality LONC.localityIdentity = L.localityIdentity/* LEFT OUTER JOINCONTAINSTABLE( tbl_category, title, @keyword ) ASt1ON FT_TBL.categoryIdentity = t1.[KEY] */LEFT OUTER JOINCONTAINSTABLE( tbl_classified, title, @search ) ASt2ON C.classifiedIdentity = t2.[KEY]LEFT OUTER JOINCONTAINSTABLE( tbl_classified, description,@search ) AS t3ON C.classifiedIdentity = t3.[KEY]WHERE ( /* COALESCE( t1.RANK, 0 ) + */COALESCE( t2.RANK, 0 ) +COALESCE( t3.RANK, 0 ) ) != 0) AS D1LEFT OUTER JOINtbl_classified_file CFOND1.classifiedIdentity = CF.classifiedIdentityLEFT OUTER JOINtbl_file FONF.fileIdentity = CF.fileIdentityWHERE( row >= @startRow )AND( @endRow IS NULL OR row <= @endRow )ENDThe part I'm having trouble with is making the sort order in thefollowing line dynamicORDER BY CASE @sort WHEN 0 THEN CAST( COALESCE( t2.RANK, 0 ) +COALESCE( t3.RANK, 0 ) AS CHAR( 5 ) ) WHEN 1 THEN C.title WHEN 2 THENCAST( CEILING( [dbo].[fn_calculateDistance] ( @fromLatitude,@fromLongitude, L.latitude, L.longitude ) ) AS CHAR( 9 ) ) WHEN 3 THEN( C.locality + ' ' + C.state ) WHEN 4 THEN CAST( C.price ASCHAR( 10 ) ) END ASCany help would be greatly apprecaited.Thanks

View 1 Replies View Related

Dynamic Order Status Column Function

Apr 7, 2008

I am looking for assistance coming up with a function (or maybe not a function if there is a better way) to make the Status column in my order table dynamic. The default value for new records will always be "1" to designate a quote. At this point the field is not dynamic. Once the customer confirms the order, the user needs to execute a command to change the status to "3" to designate a Confirmed order. At this point the field needs to be dynamic based on the shipping records. There are two order details tables. One for sales items and one for rental items. Each of these details tables has their own shipping record. the CheckInOut Tables are for rental while the Ship tables are for sales. So, if some (but not all) of the items in either of these order details tables has a shipping record associated with it, then the status should be changed to "5". If everything has been shipping, the status is changed to "4". If everything has been shipping but some items have been returned, the status is "6" if everything has been shipping and all of the RentalDetail items have been returned then the status is "7" and if there is any other combination of a variety of ships and returns, the status is "8". Also, at any time, the user needs to be able to execute a command to change the value to "2". once the value is changed to "2" the field stops being dynamic again.

Below are my tables creation commands.


CREATE TABLE OrderHeader
(
OrderID int identity primary key,
Status int,
StartDate datetime,
EndDate datetime
)--Use Type 1 = "Quote" Type 2 = "Cancelled" Type 3 = "Confirmed", Type 4 = "Shipped", Type 5 = "Part Shipped", Type 6 = "Part Returned", Type 7 = "Returned, Type 8 = "Mixed"
CREATE TABLE OrderRentalDetail
(
OrderRentalDetailID int identity primary key,
OrderID int FOREIGN KEY REFERENCES OrderHeader(OrderID),
ItemName varchar(30),
Qty int,
SiteID int,
)
CREATE TABLE CheckInOutHeader
(
CheckInOutID int identity primary key,
Type int,
SiteID int,
ActionDate datetime
)--Use Type 1 = "Ship" Type 2 = "Return" Type 3 = "Lost"
CREATE TABLE CheckInOutDetail
(
CheckInOutDetailID int identity primary key,
CheckInOutID int NOT NULL FOREIGN KEY REFERENCES ShipHeader(ShippingID),
OrderRentalDetailID int,
Qty int
)
CREATE TABLE OrderSalesDetail
(
OrderSalesDetailID int identity primary key,
OrderID int FOREIGN KEY REFERENCES OrderHeader(OrderID),
ItemName varchar(30),
Qty int,
SiteID int,
)
CREATE TABLE ShipHeader
(
ShippingID int identity primary key,
Type int,
SiteID int,
ActionDate datetime
)--Use Type 1 = "Ship" Type 2 = "Return"
CREATE TABLE ShipDetail
(
ShipDetailID int identity primary key,
ShippingID int NOT NULL FOREIGN KEY REFERENCES ShipHeader(ShippingID),
OrderSalesDetailID int,
Qty int
)

View 3 Replies View Related

T-SQL (SS2K8) :: Change Column Order In Dynamic Pivot?

Sep 17, 2014

I am creating dynamic pivot and my column order is as below

[2015-02],[2015-04] [Prior] ,[2014-08],[2014-11]

but i want to display as below:

[Prior],[2014-08],[2014-11],[2015-02],[2015-04]

View 1 Replies View Related

Help With Pagination

Sep 27, 2007

Hi,
My requirement is that when i show data the vertical scroll bar should be disabled.ie,whatever data can be accomodated in a screen should be shown and the rest should go to next page.
I have tried restricting the no of rows shown to 20 but this wont work always as the font size may change.I had used the follwing for this:
<GroupExpression>=Ceiling(RowNumber(Nothing)/20)</GroupExpression>

is there any other way???

please help...

View 1 Replies View Related

Pagination

Jan 3, 2006

Hi,



I have recently moved into ms sql from mysql and having problems with
finding a query to help paginate my search results. In mysql I would
use:



SELECT * FROM tablename WHERE something = something LIMIT 0,10



what would a similar query be in sql server?



From what I have experienced so far I know this is going to be a big query!



Thanks in advance



Steve

View 4 Replies View Related

Pagination

May 30, 2007

I have a report which consists of a list item, in which is a rectangle containing a header (as a subreport, but I think that's not relevant) and a subreport. The aforementioned rectangle is specified to include a pagebreak after each occurrence, but that pagebreak is not working as expected.

When I run the report I get 1 subreport on the first page, and exactly two on each subsequent page. Other than the pagination, I am getting very close to what I want. It's too bad that the subreport's pagination is ignored, but I can live with that for now.



Things I've already tried:

The report's pageSize and interactiveSize are both set to landscape

The subreport's report's pageSize and interactiveSize are both set to the actual size that the subreport takes up on the main report (which is ignored anyway)

The list does not have any of the page break options selected.



Any Ideas?

View 4 Replies View Related

Pagination In SQL????

Oct 1, 2007

Hi,
I have found the follwing article on internet. This article states two keywords LIMIT and OFFSET using which we can implement the pagination type of functionality in MySQL or PostgreeSQL,
http://www.petefreitag.com/item/451.cfm

But is there any way using which we can implement pagination kind of functionality in SQL.
LIke first time if i set 0 thenm it fetch the records from 1-10 then if i set 10 then it will fetch the next set of records from 11-20 like this,
Can we do it in SQL?????

View 1 Replies View Related

Pagination Without Datagrid

Mar 13, 2006

I'm working on a website where we're using .Net web services to feed data to a Flash front-end. The site will have a comments section and we want to display 15 or so comments per page with 'back' and 'next' functionalitiy. We'd also like to show the number of pages of comments and highlight the page they're on. The standard stuff that datagrids do so well. How can this be accomplished without a datagrid? There's a good page that explains a number of ways to do this using classic ASP. Some of the solutions they implement I can most likely use with .Net.http://www.aspfaq.com/show.asp?id=2120But I wanted to ask the community. How to paginate without a recordset? Sql Server 2000 back-end, ASP.NET 1.xThanks.

View 3 Replies View Related

Pagination Advice

Oct 4, 2006

Hi

I'm still quite new to MSSQL so excuse the trivial questions.
I've already tried searching through the forums on pagination as im sure its a big subject but couldn't find the answers i'm after.

I'm using MSSQL 2000 and asp .net 2.0 and basically need to paginate my results. My database contains roughly 250,000 rows of data, and one query would approximately return 30 results at the most. I would want to have 5 results per page.

I'm starting from scratch so was wondering what technique i could use. I can't use OFFSET as thats MySQL, is there an equivalent?
I've heard mixed opinions on Cursors, but so far thats the only way i can see at the moment! :S

thanks

View 1 Replies View Related

Pagination Recommendations

Apr 12, 2004

I am a PHP programmer for a small startup. We are storing person records and our MS SQL Server 2000 database has grown to the point where we wish to paginate the data before returning it to my PHP scripts.

I was wondering if anyone has any recommendations on an optimal way to manage this given the following requirements.

- Data must return only X number of rows at a time (user configurable).
- Must be able to search by several diffent criteria (name, date, birthday, location, ...)

Also, I was wondering if it is possible to return the total number of existant rows of data as the first row of a MSSQL procedure.

View 2 Replies View Related

One More Solution For A Pagination

Jul 20, 2005

Let me know what you think about the following code:DECLARE @MaxIdValue intDECLARE @MaxSortFieldValue nvarchar(50)SELECT TOP 1 @MaxIdValue = [id], @MaxSortFieldValue = [SortField]FROM (SELECT TOP PageNumber*RowsPerPage [id], [SortField]FROM MyTableWHERE (FilterCondition) ORDER BY [SortField], [id]) TORDER BY [SortField] DESC, [id] DESCSELECT TOP RowsPerPage * FROM MyTableWHERE ([SortField] >= @MaxSortFieldValue) AND (([id] > @MaxIdValue) OR([SortField] <> @MaxSortFieldValue)) AND (FilterCondition)ORDER BY [SortField], [id]This is a dynamic SQL and it should be easily fixable.PageNumber, RowsPerPage, FilterCondition and SortField are going to bethe variables and will be based on the user's searchcondition/criteria.-----------------------------Thanks for you attention.

View 2 Replies View Related

Pagination Is Not Working

Jan 17, 2007

Hi,

I have a problem with paging in my report. My report is quite simple, I have a table with two grouping levels. Paging is not appearing besides there is a lot of rows displayed.

When I change the report to use only one grouping level, the paging works fine. Is paging being calculated on the first grouping level ? I have about 10 to 20 rows at the first level but about 1500 rows on the second one.

Any help will be appreciated.

View 4 Replies View Related

Pagination With Row Count

Nov 17, 2007


I changed a stored procedure that does pagination from the top style to the
bottom style - mainly to avoid errors in differences in the 2 queries (count
and select) and for conciseness. The performance on a large table for the
bottom query was amazingly bad. The query plan is very different too. It
was about 25 times slower on a 1 million row table. I am familiar with
other pagination techniques (temp tables with identity, TOP-TOP, etc), but
is there a way to use the ROW_NUMBER function AND get a count of records
back in a single query with decent performance?


-- -------------------------------------------------------------
USE NorthWind


DECLARE @cnt Int
SELECT @cnt = Count(*) FROM Customers


;WITH Cust AS
(
SELECT CompanyName, ContactName,
ROW_NUMBER() OVER (ORDER BY ContactName) AS rownum
FROM Customers
)
SELECT *, @cnt AS TRowCount
FROM Cust
WHERE rownum > 10
AND rownum <= 20
ORDER BY rownum
-- -------------------------------------------------------------
-- -------------------------------------------------------------
USE NorthWind


;WITH Cust AS
(
SELECT CompanyName, ContactName,
ROW_NUMBER() OVER (ORDER BY ContactName) AS rownum,
Count(*) OVER() AS TRowCount
FROM Customers
)
SELECT *
FROM Cust
WHERE rownum > 10
AND rownum <= 20
ORDER BY rownum
-- -------------------------------------------------------------

View 10 Replies View Related

Dynamic Sort Column And Sort Order Not Working

Aug 7, 2007

I am trying to set sorting up on a DataGrid in ASP.NET 2.0.  I have it working so that when you click on the column header, it sorts by that column, what I would like to do is set it up so that when you click the column header again it sorts on that field again, but in the opposite direction. I have it working using the following code in the stored procedure:   CASE WHEN @SortColumn = 'Field1' AND @SortOrder = 'DESC' THEN Convert(sql_variant, FileName) end DESC,
case when @SortColumn = 'Field1' AND @SortOrder = 'ASC' then Convert(sql_variant, FileName) end ASC,
case WHEN @SortColumn = 'Field2' and @SortOrder = 'DESC' THEN CONVERT(sql_variant, Convert(varchar(8000), FileDesc)) end DESC,
case when @SortColumn = 'Field2' and @SortOrder = 'ASC' then convert(sql_variant, convert(varchar(8000), FileDesc)) end ASC,
case when @SortColumn = 'VersionNotes' and @SortOrder = 'DESC' then convert(sql_variant, convert(varchar(8000), VersionNotes)) end DESC,
case when @SortColumn = 'VersionNotes' and @SortOrder = 'ASC' then convert(sql_variant, convert(varchar(8000), VersionNotes)) end ASC,
case WHEN @SortColumn = 'FileDataID' and @SortOrder = 'DESC' THEN CONVERT(sql_variant, FileDataID) end DESC,
case WHEN @SortColumn = 'FileDataID' and @SortOrder = 'ASC' THEN CONVERT(sql_variant, FileDataID) end ASC  And I gotta tell you, that is ugly code, in my opinion.  What I am trying to do is something like this:  case when @SortColumn = 'Field1' then FileName end,
case when @SortColumn = 'FileDataID' then FileDataID end,
case when @SortColumn = 'Field2' then FileDesc
when @SortColumn = 'VersionNotes' then VersionNotes
end

case when @SortOrder = 'DESC' then DESC
when @SortOrder = 'ASC' then ASC
end  and it's not working at all, i get an error saying:  Incorrect syntax near the keyword 'case' when i put a comma after the end on line  5 i get: Incorrect syntax near the keyword 'DESC' What am I missing here? Thanks in advance for any help -Madrak 

View 1 Replies View Related

Limiting Result For Pagination

Aug 5, 2004

Hello,

We are migrating from VB6/MySQL to VB6/MS SQL.

The application retrieves limited records for paginated results.
This way we can access large databases, but only return rows for one screen.

For example:
Select row 1 - 10, then 11 - 20 then 21 to 30 etc.

With MySQL we can use LIMIT and OFFSET and it works great.
MySQL
SELECT <columns> FROM <tables> [WHERE <condition>] [ORDER BY <columns>]
[LIMIT [offset,]howmany>]

Does anybody know how we can do something similar with MS SQL?

Any feedback is appreciated!

Thank you,

Edi

View 2 Replies View Related

Pagination For Large Data

Jul 20, 2005

I want to build a system that will have about 1 million rows in atable in sql server database.I am using this for a web application andaccessing it via JDBC type 4 driver.But display 20 records at a timeonly using pagination(as in google).What will be the best way to goabout this.

View 1 Replies View Related

SSRS &&amp; FIREFOX - Pagination

Mar 6, 2008

I would like to know how to show all the records returned (upto 1000) in one single page on a web browser. I am able to get the required report in IE but in case of Firefox it hangs.

Did some test and found that Firefox is able to render a report of upto max 300 records in a single page without getting hanged but report is coming very slow. While you scroll the scroll bar it€™s moving with Jerks. with 200 records in a single page is not getting hanged but report is faster than 300 records display. But by 500 records Firefox hangs. I understand it might be depending on the hardware also but am not sure.

Can anybody give me a good solution to display upto 1000 records in a single page or if its a limitation, where can i get the documentation of it.

Thanks and regards
Niaz Khan

View 8 Replies View Related

Report Pagination For Charts

Feb 15, 2007

Hi,

We have developed few reports displaying data using chart layout. In the Data tab, we have specified MDX query that will return top 10 records.

But now, instead of restricting to just top 10 records, we would like to display all records and go in for pagination.

Is there some setting in the chart properties, where in I can display the first n records in first page, and the next n records( if available) in the next page and so on?

Can I specify the value of n somewhere in the propeties?

I read through many posts regarding pagination but those couldn't help me much.

Please help me in solving this problem.

Any help would be appreciated.

Thanks in advance!

View 5 Replies View Related

Get Total Records While Using ROW_NUMBER() For Pagination

Oct 29, 2007

I've got the following query:

WITH OrderedResults AS (SELECT some_table.*, ROW_NUMBER() OVER (ORDER BY some_field) as RowNumber FROM some_table)
SELECT TOP 10 *
FROM OrderedResults
WHERE RowNumber > 10;

which works well for returning "paginated" recordsets. But when it comes to displaying "page" links and next and previous links, I need a total count of records found... something along the lines of the MySQL CALC_FOUND_ROWS feature...

Is there some built-in MSSQL feature I can use for this, or do I have to do a SELECT count(*) FROM some_table to get this data?

Any advice is appreciated

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved