View Ignoring Order By - Used To Work In Sql 2000
Dec 13, 2005This works fine in SQL 2000, but not in SQL 2005
View 12 RepliesThis works fine in SQL 2000, but not in SQL 2005
View 12 RepliesI have just transferred my site to a new server with SBS R2 Premium, so the site's database changed from SQL 2000 to SQL 2005. I find that searches are now returning results in random order, even though they use a view with an Order By clause to force the order I want.
I find that the results are unordered when I test the view with Management Studio, so the issue is unrelated to my VB/ASP Net code.
Using my SQL update tool (SQL Compare, from Redgate) I find that there are no differences in the views, or the underlying tables.
Using Management Studio to test a number of views, I find that I have a general problem with all views. For example, one of the simpler views is simply a selection of fields from one table, with an Order By clause on the tables primary key: - SELECT TOP (100) PERCENT GDQid, GDQUser, GDQGED, GDQOption, gdqTotalLines, GDQTotalIndi, GDQRestart, GDQCheckpointMessage, GDQStarted, GDQFinished, gdqCheckpointRecordCountr FROM dbo.GEDQueue ORDER BY GDQid DESC
If I right-click the view (from Management Studio's Object Explorer pane), select Design from the menu to show the view's design, and then click the Execute SQL icon, the view's results are displayed perfectly, in descending order of GDQid. However, if I select "Open View" the view's results are displayed out of order.
When I do this with the SQL 2000 database, both Design/Execute and Open View correctly display the data in the correct order.
Is there something that I should check in the SQL 2005 installation - some option that has been set incorrectly?
Regards, Robert Barnes
Hi,
I'm using the following SQL script to return a list of part number and the order is not what I expect. Perhaps this is a collation problem but I have no idea where to look to modify that.
Thanks in advance, John
select part from transactions T where (T.transdate between '20070701' and '20070705') and
(T.transtype = 'ISSU' or T.transtype = 'RTRN') order by part
Here is the beginning of the Transactions table create script
CREATE TABLE [Transactions] (
[RecNo] [int] IDENTITY (1,1) NOT NULL,
[Part] [nvarchar] (30) NOT NULL ,
[TransDate] [nvarchar] (8) NOT NULL ,
[TransType] [nvarchar] (4) NOT NULL ,
[FromLoc] [nvarchar] (10) ,
The 'Part' column is an alphanumeric field. The problem I am having is that the
Order By seems to ignore the hyphen character '-' when the returned rows
are ordered by the Part (which can contain hyphens in any column).
Here is an example of what I get.
130909N9
130909N9
130909N9
1-480698-0 * These two should not be here
1-480699-0 *
15-423
164-07700
164-07700
164-07700
1683
I was expecting this ( and I get this in and older database ).
068-03000
068-03000
06A19956
074-03200
077-367-0
08DU08
1-480698-0 * These should be here eariler in the data
1-480699-0
100-364072
100-364072
I have a table:
CREATE TABLE [dbo].[tx1]( [f1] [nvarchar](50) , [seq] [int] IDENTITY(1000,1) NOT NULL ) ON [PRIMARY]
SELECT *
FROM dbo.tx1
ORDER BY seq DESC
go
f1 seq
zz 1003
uu 1002
kk 1001
yy 1000
create view vx1 as
SELECT top 100 percent *
FROM dbo.tx1
ORDER BY seq DESC
go
select * from vx1
yy 1000
kk 1001
uu 1002
zz 1003
I have created view by jaoining two table and have order by clause.
The sql generated is as follows
SELECT TOP (100) PERCENT dbo.UWYearDetail.*, dbo.UWYearGroup.*
FROM dbo.UWYearDetail INNER JOIN
dbo.UWYearGroup ON dbo.UWYearDetail.UWYearGroupId = dbo.UWYearGroup.UWYearGroupId
ORDER BY dbo.UWYearDetail.PlanVersionId, dbo.UWYearGroup.UWFinancialPlanSegmentId, dbo.UWYearGroup.UWYear, dbo.UWYearGroup.MandDFlag,
dbo.UWYearGroup.EarningsMethod, dbo.UWYearGroup.EffectiveMonth
If I run sql the results are displayed in proper order but the view only order by first item in order by clause.
Has somebody experience same thing? How to fix this issue?
Thanks,
Hi,
A quick background on the problem;
My company is in the process of a migration from Windows Advanced Server 2K, SQL 2K to Server 2003 and SQL 2005. I'm not certain of the exact process used by our DBA to convert the DB, but I can access it, and all my tables/views/sprocs appear to be in the right place.
I copied all my web files to our new server after the DBA was done with her job, made a new user on the new instance of SQL server, changed a few connection strings in my global.asa and global.asax, and ta-dah! Just like magic, the new site opened on our new servers without much resistance.
Except....
None of the content on our sites is sorted. I cannot seem to get ORDER BY statements to work at all. They appear to be disregarded by SQL server when not in MODIFY mode for a particular view (in SQL Server Management Studio).
So, when I MODIFY a view, add criteria (NOT SORT), save the changes, then OPEN, the criteria is respected. The filter is applied. BUT...
If I MODIFY a view and add a SORT using ORDER BY (by hand or with the Manager) the sort is NEVER respected when the view is Opened through the manager or in my code.
If I open any sorted view and then click MODIFY, and then RUN (without making ANY changes), the sort works with no problem whatsoever.
To summarize/restate my case, if I OPEN any view in the system that has an ORDER BY criteria, the sort is NOT APPLIED. If I instead right-click and MODIFY, then click RUN, the SORT is APPLIED.
I've tried sorting datetime and text fields, all with the same results - none. This single dumb issue has been delaying the migration of our servers for days!
Can anyone help?
Thanks always in advance,
Drew
when i try the following SQL batch, I get a result-set which is not order by
datetime column 'out_date',but if I delete clause INTO #fifo_temp, I get a correct result with correct order.
who can help me?thanks in advance
...
select tag,stuff_id,stuff_name,cast(out_id as char(10)) as out_id,out_number,out_date,out_qty,remark
INTO #fifo_temp from ##stuff_fifo UNION
select tag,stuff_id,stuff_name,out_id,null,out_date,quant ity,remark
from acc_cost.dbo.stuff_out where tag='A' and left(out_id,3) in ('XSA','TAP')
ORDER BY out_date
DROP TABLE ##stuff_fifo
select * from #fifo_temp
the following can get a correct result:
select tag,stuff_id,stuff_name,cast(out_id as char(10)) as out_id,out_number,out_date,out_qty,remark
from ##stuff_fifo UNION
select tag,stuff_id,stuff_name,out_id,null,out_date,quant ity,remark
from acc_cost.dbo.stuff_out where tag='A' and left(out_id,3) in ('XSA','TAP')
ORDER BY out_date
Hello
Iam usng sql server 2005 database
I had this table
CREATE TABLE [dbo].[Companies](
[CompanyID] [smallint] IDENTITY(1,1) NOT NULL,
[Company] [nvarchar](40) NOT NULL,
I entered Arabic Names
so I write this query
select * from companies order by company asc
--and this one
select * from companies order by company
and I try to order desc
but the row didnt appear out ordered
and the big prtoblem happened when I try to update a company Its go to the last row when it appears
please help me
thanks
the select statement in the join orders the numbers asc and if you run everything below the case statement it works, but as you run the whole thing the order is no longer there.
I need the order to work. What am I missing?
--Assign Intern's students
Update tblObjectType3_14
Set [FldNumeric23764]= case when tID = 1 and Q.n <= 100 then 2
when tID = 2 and Q.n <= 150 then 2
when tID = 3 and Q.n <= 150 then 2
when tID = 4 and Q.n <= 130 then 2
[code]....
Can someone tell me why SQL seems to ignore my order by clause?I tried to run through the debugger, but the debugger stops at theselect statement line and then returns the result set; so, I have noidea how it is evaluating the order by clause.THANK YOU!CREATE proc sprAllBooks@SortAscend varchar(4),@SortColumn varchar(10)asIf @SortAscend = 'DESC'Select titles.title_id, title, au_lname, au_fname,Convert(varchar(12), pubdate, 101) as PubDatefrom authorsinner jointitleauthoronauthors.au_id = titleauthor.au_idinner jointitlesontitleauthor.title_id = Titles.title_idORDER BY au_lnameCASE @SortColumn WHEN 'title' THEN title END,CASE @SortColumn WHEN 'au_lname' THEN au_lname END,CASE @SortColumn WHEN 'PubDate' THEN PubDate ENDDESCELSESelect titles.title_id, title, au_lname, au_fname,Convert(varchar(12), pubdate, 101) as PubDatefrom authorsinner jointitleauthoronauthors.au_id = titleauthor.au_idinner jointitlesontitleauthor.title_id = Titles.title_idORDER BYCASE @SortColumn WHEN 'title' THEN title END,CASE @SortColumn WHEN 'au_lname' THEN au_lname END,CASE @SortColumn WHEN 'PubDate' THEN PubDate ENDGO
View 7 Replies View RelatedHello all,The followinq qurey returns sometimes values of null to some of this columns, byK,byT,byD. the column F wil not contains any nulls, and 0 will be populated in it at any case of .Now, the problem is that when sorting out F the sort will not work when there is null parameters in byK because teh fact that a 0 values is greater then NULL value, and the sort of F will not take in considiration. So I guess the question is how can I sort NULL values and 0 values to be the same weight in the sort by command? SELECT A.gym_id as gym,s_id, week, gym_name, boxer, league, sum(points)
points,sum(byK)as byK, sum(byT) as byT,sum(byPoints) as byPoints ,
sum(byD) as byD, count(C.gym) as F
FROM A inner JOIN B ON A.gym_id = B.gym_id
left JOIN C ON A.gym_id = C.gym
WHERE (B.l_id = ?text
group by A.gym_id
order by points DESC,byK DESC,byT DESC, byPoints DESC, byD DESC,F ASC
Hi all,
I'm getting this "invalid descriptor index" exception while trying to fetch a record from the table.
The query is "select * from <tablename> where <columnname> = 'xyz'". The column name is correct and indeed a record with 'xyz' value exists. The record is getting fetched too...! But I'm having this particular error while trying to retrieve a couple of fields with rs.getString().
The order of columns in the table is same as the order in which I'm retrieving them. And I'm not facing any problem retrieving another field which has width of 200 characters.
I'll be very grateful indeed if someone can help me out of this particular problem...
Cheers, mates!
I have a view in SQL SERVER 2005 which includes ORDER BY in my SQL expression.
When I press "execute", the results of the view come out ordered by the selected field, as they should be.
When I close the view and choose "Open View", the results come out not ordered. The same thing happens when I'm trying to show the results in a GridView.
Why does it happen?
I have to provide the Order by Value from Front End (VB) to the DB , so that I can receive the Crystal Report in the order that I have given.
thanks in advance... :confused:
In MSSql,"Order by" and "distinct" can be used in view?
thanks!
i m required to use order by in a view, how to do it, simple order by doesn't work for it, any other way,i have heard there is one in oracle, but wat abt SQL Server???:confused:
View 2 Replies View RelatedI have make a view where i have a order by
when i execute my view in modify my result are allright
but when i say open view to see my view it is not
in order by.
I use the view in a asp site to the internet and i can't use order by here
because the field i orderby shall not come up in my site, i only use this field
to order by
Hope someone can help
Alvin
InfoPath 2003
I have an Infopath form to edit the values in the NotifyMembers table. I want to list the email addresses alphabetically when the query returns data to the form. Unfortunately, I use EmailAddressID as an int in the table, so I need to join? the NotifyMember table with the EMailAddress table, which has a column EMail which is the address. Both have EmailAddressID as common fields.
I can't get the Shape command (edit SQL in the Datasource) to be happy with any syntax that I have tried.
For (non-working) example:
select "GroupCode","EmailAddressID","DelBit" from "dbo"."NotifyMembers" as "NotifyMembers" Join "dbo"."NotifyMembers"."EmailAddressID" On "dbo"."EmailAddress"."EmailAddressID" = "dbo"."NotifyMembers"."EmailAddressID" order by "dbo"."EmailAddress"."Email"
Any help appreciated..
I'm using a Contoso database running on Power BI Desktop (Version: 2.28.4190.122). The databiase is actually a Contoso.pbix file provided for a book [URL]. I have a DAX query that summarizes a Products table by Product[Manufacturer] and gives a count of products by the manufacturers.My Problem is that the ORDER BY COUNTROWS doesn't work.
why the order by clause doesn't work when I'm confined to the Products table while the order by clause does work when I start with the Sales table? The numbers are correct in both queries.
This query doesn't sort
EVALUATE
SUMMARIZE (
Product,
Product[Manufacturer],
"ProductCount", COUNTROWS ( Product )
)
ORDER BY COUNTROWS ( Product ) DESC
This query does sort correctly
EVALUATE
SUMMARIZE (
Sales,
Product[Manufacturer],
"ProductCount", COUNTROWS ( RELATEDTABLE ( Product ) )
)
ORDER BY COUNTROWS ( RELATEDTABLE ( Product ) ) DESC
I have downloaded and installed SQL Server Express 2003 Adv.. I have created a new database in it and also a table called Customers. In that I have created one field called CustomerName as nvar(255). I have made 10 records by filling in the field with various names. I have then created a new view and asked it to order the records in descending order. When I save and show the view it shows the records still in the order that I inserted them not in descending alphabetical order. If I make it show in ascending order the same problem still occurs. Collation settings are correct for the computer at Latin1. However, I have tried a few others, but none make any difference. SQL Server Express 2003's view will not list my Customers in either ascending or decending alphabetical order. Can anyone give me any suggestions?
View 4 Replies View RelatedI have the view below and if I use vwRouteReference as the rowsourcefor a combo box in an MS Access form or run "SELECT * FROMvwRouteReference" in SQL Query Analyzer, the rows don't come throughsorted by Numb.Everything I've read on the web suggests that including the TOPdirective should enable ORDERY BY in views. Does someone have an ideawhy the sorting is not working correctly for this particular view? thanks.CREATE VIEW vwRouteReferenceASSELECT TOP 100 PERCENT tblItem.ID,tblItem.Numb + ' - ' + tblQuestion.DescrPrimary AS FullName,tblItem.Numb, tblQuestion.DescrPrimary AS TypeFROM tblItem INNER JOIN tblQuestionON (tblItem.ID = tblQuestion.Item_ID)WHERE (((tblItem.Category_ID)>0))UNIONSELECT TOP 100 PERCENT tblItem.ID,tblItem.Numb + ' - ' + tblItem.Type + ' : ' + tblItem.Class AS FullName,tblItem.Numb, tblItem.Type + ' : ' + tblItem.Class AS TypeFROM tblItemWHERE (((tblItem.Type) = 'Assignment' OR (tblItem.Type) = 'Check' OR(tblItem.Type) = 'Route'))ORDER BY tblItem.Numb
View 49 Replies View RelatedWhen I create a view in SQL and include an ORDER BY clause i can see itin Management Studio. However, when I call the same view from an ASPpage the order goes completely haywire.Any ideas?
View 24 Replies View Related
Hi,
I have created a view which uses 3 tables, i also have a sort on one of the columns. However when I open the view the sort does not work. It does however sort the view correctly when executing the query within design view
Can anyone explain this or is it a bug within SQL Server Express 2005?
thanks
David
Hello,
I am trying to create a simple view which uses self joins. I want the final result order by. I am able to create the view using Top clause followed by order by but when I simply query the view it does not appear in the correct order. Can some body help me with the issue.
CREATE VIEW [dbo].[vw_SalesRep_Chaining]
AS
SELECT Top 100 percent Rep_id AS RepId,
Rep_cd AS RepCode,
Region as Region,
CASE WHEN Market IN ('Arizona - North', 'Arizona - South', 'Gtr TX / New Mexico') THEN 'Arizona / New Mexico'
WHEN Market IN ('L.A. Metro - West', 'L.A. Metro - North', 'L.A. Metro - East') THEN 'LA Metro'
WHEN Region = 'Western' AND Market NOT IN ('Arizona - North', 'Arizona - South', 'Gtr TX / New Mexico', 'L.A. Metro - West', 'L.A. Metro - North', 'L.A. Metro - East') THEN 'Western - Other'
ELSE '' END AS Sub_Region,
RSM AS RSM,
UPPER(Regional_Manager) AS Regional_Manager,
Market,
Rep_Manager_id AS SalesManager,
UPPER(MarketManager) AS MarketManager,
New_Position AS NewPosition,
Rep_Status AS RepStatus,
UPPER(Rep_Payroll_name) AS PayrollName
FROM (SELECT SalesRep_GUID, Rep_id, Rep_cd, Rep_Payroll_name, Rep_SSN, Rep_Status, Hire_dt, Termination_dt, Commission_start_dt,
Rep_Manager_id, Region, Market, New_Position, Validity_start_dt, Validity_end_dt, Load_interval_id, Create_process_id, current_ind
FROM dbo.SalesRep
WHERE (current_ind = 1) AND (New_Position IN ('SC1', 'SC2', 'SC3', 'MSO')) AND (Region NOT IN ('Emerging Market')) OR
(current_ind = 1) AND (New_Position IS NULL) AND (Region IN ('TeleSales')) AND (Region NOT IN ('Emerging Market'))) AS A
INNER JOIN (SELECT Rep_id RepId, Rep_Payroll_name as MarketManager, Rep_Manager_id as RSM
FROM dbo.SalesRep AS SalesRep_2
WHERE (current_ind = 1)) AS B
ON A.Rep_Manager_id = B.Repid
INNER JOIN (SELECT Rep_id RepId1, Rep_Payroll_name as Regional_Manager FROM dbo.SalesRep AS SalesRep_1
WHERE (current_ind = 1)) AS C
ON B.RSM = C.Repid1
WHERE (A.Region IS NOT NULL)
Order by Rep_Id, Rep_Cd
This is the script I have used to create the view. But when is simply query the view it does not appear in the order of Rep_Id, Rep_Cd
Hi there,
I have a view created using the following code. The view works perfectly but does not order by the name column as I've asked it to do. In the view designer if I click on execute then the order is applied but if I save the view and run it externally (i.e. in an ASP page or within the management terminal) it does not order correctly and seems to order by the Id column.
Any help would be much appreciated. Here's the code:
SELECT TOP (100) PERCENT dbo.Members.DivisionID, COUNT(*) AS Members, dbo.Country.Name
FROM dbo.Members INNER JOIN
dbo.Country ON dbo.Members.DivisionID = dbo.Country.CountryID AND dbo.Members.CountryID = dbo.Country.CountryID
GROUP BY dbo.Members.DivisionID, dbo.Country.Name
ORDER BY dbo.Country.Name
And another, more simpler view, that doesn't sort as it's supposed to.
SELECT TOP (100) PERCENT CountryID, Name, RegionID, IsActive, HasFlag, URL, Comments
FROM dbo.Country
ORDER BY Name
Many thanks,
Ady
Hi,
I've a problem with a created view in sqlserver2000 that I'm now using in sqlserver2005.
This is the view :
CREATE VIEW hsarti01_VD1 AS
SELECT TOP 100 PERCENT *
FROM hsarti01 WITH(index(hsarti01_PK))
ORDER BY 1,2 desc,3,4
When I do the "select * from hsarti01_VD1" in sql server 2000, I see in the result that the order by is been using. but in sql server 2005 it's just using the order of the primary key and not the order by !
Has anyone have a solution for it ?
Thanks
I built a view that runs against the aspnet_WebEvent_Events table, part of the ASP.Net Health Monitoring.
Here is the view SQL:
SELECT TOP (100) PERCENT EventTime, EventType, EventSequence, EventOccurrence, EventCode, EventDetailCode, Message, ApplicationPath,
ApplicationVirtualPath, MachineName, RequestUrl, ExceptionType, Details
FROM dbo.aspnet_WebEvent_Events
ORDER BY EventTime DESC
What I found is that when the query is ran within the View Designer that the view is ordered by the correct EventTime (datetime) field.
But when the view is ran from right-clicking on the view and selecting "Open View" the order by does not take place.
Why is this happening and how do I fix it?
I am using BCP utility to export data from a view to text file. I get the following error
"Copy direction must be either r 'in', 'out' ..." when I execute the following
exec master..xp_cmdshell 'bcp [Salesforce_Prod].[dbo].[Project With Opps] out c: est99.txt -c -t, -T -S'
The same thing work if I replace the view in the statement above with a table name.
Hallo
I got a Link Server (IBMDASQL) and a view. And I am wondering how a view works.
If I try:
select * from [myView] where [myView].A = @A
Dos the Link Server retrieve the complete table and the SQL server applies the where condition?
Or
Does the Link Server use the where condition and retrieve just the requested records?
I created a view V1 that uses an outer join with a table and calls a sub-view VS1 (ds_proj_report_date) which uses an inner join) and does an inner join with VS1. I also created another view V2 that uses inner join but does not call the sub-view VS1.
When I run the two views as below it works fine
Select * from V1
Union
Select * from V2
I then created another view V3 of the above union as
Create view V3
As
Select * from V1
Union
Select * from V2
Now when I run select * from V3, I get the following error.
Joined tables cannot be specified in a query containing outer join operators. View or function 'ds_proj_report_date' contains joined tables
I'm just wondering what is the resolution or execution order for a query like this (simplified version):
CREATE VIEW ClosedSales AS
SELECT *
from NatSales
where CurrentFlag = 1
and ValidTo <> '9999-99-99'
Select * from ClosedSales
where CustomerId = 10
The thing I want to know is:
- If first the complete dataset from the view is calculated and the the CustomerId=10 filter is applied
- Or the CustomerId=10 condition is added to the where clause in the view definition
My real case is much more complex but that is an interesting point in my performance analysis.
hi guys,
i've been asked to re-write a sql view. the view itself contains several calls to other views (embedded). is there a way to get around using embedded views. I've written the same query up using temp. tables but obviously temp. tables can't be used in views?
Is there any special things I should be looking for?
My Table Structure
Category_ID Number
Parent_ID Number <----Category_ID reports to this colum
Category_Name Varchar....
MY QUERY <---I replaced the query above with my data
=============================
WITH Hierarchy(Category_ID, Category_Name, Parent_ID, HLevel)
AS
(
SELECT Category_ID, Category_Name, Parent_ID, 0 as HLevel FROM Dir_Categories
UNION ALL
SELECT SubCategory.Category_ID
, SubCategory.Category_Name,
SubCategory.Parent_ID,
HLevel + 1
FROM Dir_Categories SubCategory
INNER JOIN Hierarchy ParentCategory
ON SubCategory.Parent_ID = ParentCategory.Category_ID )
SELECT Category_ID,
Category_Name = Replicate('__', HLevel) + Category_Name,
Parent_ID,
HLevel
FROM Hierarchy
My OUTPUT============
All the categories under reporting to Parent_ID 0 or continuous, then the ones reporting to 1 and so fourth. Subcategories are not showing within their main categories. I AM GOING NUTS WITH THIS.
Can you help me please?