Showing posts with label clause. Show all posts
Showing posts with label clause. Show all posts

Friday, March 23, 2012

Question on Top N clause

Top N clause retrieve the first N rows of the table. How can I retrieve the second N rows? Generally , is there any solution to retrieve the nth N rows?Daniel Anderson has an article at 4GuysFromRolla which contains a general solution:Paging through Records using a Stored Procedure.

You could also do it non-generically and unattractively and probably inefficiently like this (will select records 11-20):

SELECT TOP 10 * FROM
(SELECTTOP 10 * FROM
(SELECT TOP 20 * FROM division ORDER BY div_code ASC ) AS myTop20
ORDER BY div_code DESC) AS myTop10Desc
ORDER BY div_code ASC

Terri|||Thank you very much.|||tmorton.. that's just sexy!

Wednesday, March 21, 2012

Question on SQL Server2000s order by clause

Hi,
I have problem of order by clase.
Must I specify the column in both select clause and order by clause
so as to get the correct result?

If I omit the order by column in select clause(for example:
select order.*, cl.ID from T_ORDER order, T_CLIENT cl where ... order by cl.code),
would MS SQL server 2000 still correctly or ignore order by clause completely?


It seems the latter actually happens.

BTW, how would other DBMS handle this case?

Regards,
Justinin SQL the ORDER BY clause is independent of the actual query is so far as you can sort by a column that is not listed in the select list

for example

select fname , lastname, middle
from t1
order by zipcode

on a side note you can also order by the ordinal number of the columns in the result set but this is confusing and not good form

ex
select fname , lastname, middle
from t1
order by 2

does this answer your question?sql

Tuesday, March 20, 2012

Question on SELECT * TOP 100 FROM TheTable

I have a question about how the TOP n clause works on the SELECT
statement.
Assume I have a table called TheTable that contains 10,000,000 rows
and no indexes.
Assume I execute the following SQL...
SELECT * TOP 100 FROM TheTable WHERE TheField = "12345"
Will SQL Server first do a TableScan to find ALL the rows that meet
the WHERE clause and THEN give me the TOP 100, or is it clever enough
to stop the TableScan when 100 matching rows have been found?
Thanks for any help.
RichardF> Assume I have a table called TheTable that contains 10,000,000 rows
> and no indexes.
Why would you ever have such a table?

> Will SQL Server first do a TableScan to find ALL the rows that meet
> the WHERE clause and THEN give me the TOP 100, or is it clever enough
> to stop the TableScan when 100 matching rows have been found?
Run your query, turn on execution plan, and check it out...|||Thanks for your 'help'.
It is a hypothetical table.
My question is about how SQL Server acts on the TOP n clause when one
of the fields involved in the WHERE clause is not indexed.
RichardF
On Thu, 10 Mar 2005 12:53:14 -0500, "Aaron [SQL Server MVP]"
<ten.xoc@.dnartreb.noraa> wrote:

>Why would you ever have such a table?
>
>Run your query, turn on execution plan, and check it out...
>|||> Thanks for your 'help'.
I'm trying to teach you how to analyze these things yourself. Teach someone
to fish, rather than just handing them a fish, that kind of thing. Sorry if
that help isn't good enough for you.
If it is, then create a smaller table, select a smaller percentage, and the
direction the engine takes (which you can view in Query Analyzer if you turn
execution plan on) should be roughly equivalent.
Without more information, I think it is impossible for anyone to give you a
black and white answer. There are dozens of variables aside from index
existence that contribute to whether a scan is used and when the engine
knows to stop searching. So you are probably better off testing against the
kind of data you are working with anyway.|||If the query is as simple as this, then SQL-Server will start a table
scan. During the table scan the matching rows will be returned. If a
100th row is found, the table scan will stop.
You can test this by creating this hypothetical table, and filling it
with an ascending value for "TheField". Then you can measure the
performance difference between
SELECT TOP 1 * FROM TheTable WHERE TheField=1 -- Should be fast
and
SELECT TOP 1 * FROM TheTable WHERE TheField=10000000 -- Could be slow
Hope this helps,
Gert-Jan
RichardF wrote:
> I have a question about how the TOP n clause works on the SELECT
> statement.
> Assume I have a table called TheTable that contains 10,000,000 rows
> and no indexes.
> Assume I execute the following SQL...
> SELECT * TOP 100 FROM TheTable WHERE TheField = "12345"
> Will SQL Server first do a TableScan to find ALL the rows that meet
> the WHERE clause and THEN give me the TOP 100, or is it clever enough
> to stop the TableScan when 100 matching rows have been found?
> Thanks for any help.
> RichardF|||Like Gert-Jan and Aaron said: You have to experiment. From what I could
tell, SQL Server stops searching the table when it finds enough rows to
satisfy the TOP X requirement. If you leave off of TOP requirement (or
there aren't enough rows to fulfill the TOP X) then the entire table will be
scanned.
Of course if this was a production table that was being queried quite often,
you could want an index. :)
-- Create temp table
-- =================
CREATE TABLE #test (col int NOT NULL)
GO
-- This will take awhile... (5 million rows in my test database)
-- ========================
INSERT INTO #test
SELECT CHECKSUM(NEWID()) FROM sysobjects S1,sysobjects S2,sysobjects
S3,sysobjects S4,sysobjects S5
GO
-- Start experimenting. Turn on "Show Execution Plan' and "Show Server
Trace"
-- ========================================
==============================
SELECT TOP 0 col FROM #test WHERE col = '779668530'
SELECT TOP 1 col FROM #test WHERE col = '779668530'
SELECT TOP 2 col FROM #test WHERE col = '779668530'
SELECT col FROM #test WHERE col = '779668530'
-- Find out which values of "col" are repeated
-- For use in the previous "experimenting" calls
-- ========================================
=====
SELECT *, count(*) FROM #test
group by col having count(*) > 1
"RichardF" <noone@.nowhere.com> wrote in message
news:sm1131tr8v8muj14huhtrtvnjevdkkvirf@.
4ax.com...
>I have a question about how the TOP n clause works on the SELECT
> statement.
> Assume I have a table called TheTable that contains 10,000,000 rows
> and no indexes.
> Assume I execute the following SQL...
> SELECT * TOP 100 FROM TheTable WHERE TheField = "12345"
> Will SQL Server first do a TableScan to find ALL the rows that meet
> the WHERE clause and THEN give me the TOP 100, or is it clever enough
> to stop the TableScan when 100 matching rows have been found?
> Thanks for any help.
> RichardF

Wednesday, March 7, 2012

Question on FOR XML issue

Hi, all.

I'm trying to become smarter about the use of the FOR XML clause in SQL
Server. There's one question I'd like to ask that I've not found
directly answered elsewhere, probably due to my own inaccurate or
feeble (or both) searching, so I thought I'd ask the good folks here
for a little information if I may.

I've played with the FOR XML AUTO, ELEMENTS variation of the XML
capability, and it is marvelous for what I would call "cleanly"
hierarchical data, and by that I naively mean always one-to-many
relationships.

The data I'm trying to model has, at a basic level, several one-to-many
relationships, eg Parent has many children of type X, and many children
of type Y. X and Y, themselves, are unrelated. When I write the query
to dump this data, however, SQL Server tries to wrap Y records as
children of X records, which is not correct. Another way of thinking
about it might be a list of PERSONS, and there is a BOOKS table of
favorite books for each person, and a table of favorite TV shows for
each person. BOOKS and TV are unrelated.

EG

Select Person.Lastname,Parent.Firstname,Books.Title,TV.Sh owTitle
from Person
join BOOKS
on Person.PersonID=Books.PersonID
join TV
on Person.PersonID=TV.PersonID
for XML AUTO, ELEMENTS

And I'd like to see:

<PERSON>
<Lastname>somevalue</Lastname>
<Firstanme>somevalue</Lastname>
<BOOKS>
<TITLE>Moby Dick</TITLE>
</BOOKS>
<BOOKS>
<TITLE>Hunt for Red October</TITLE>
</BOOKS>
<TV>
<ShowTItle>Laverne and Shirley</ShowTitle>
</TV>
</PERSON
But I get something more on the order of this:

<PERSON>
<Lastname>somevalue</Lastname>
<Firstname>somevalue</Firstname>
<BOOKS>
<TITLE>MOBY DICK</TITLE>
<TV>
<SHOWTITLE>Laverne and Shirley</ShowTitle>
</TV>
</BOOKS>
</PERSON
At a first glance, it doesn't seem to me there's a way to solve
this, because the joins inevitably create the appearance of a
relationship between the two "inner" pieces of data even though it
doesn't really exist. Perhaps I'm merely writing the query incorrectly,
but as I try to think of ways to rearrange it, it seems I'm just moving
the same problem around. Is there a way to solve it? Would it be
smarter just to break the queries up into separate XML exports, eg a
BOOKS.XML and a TV.XML, then combine them?

If I'm being unyieldingly stupid in not seeing the answer to this,
please accept my humble apologies in advance.

Your help is greatly appreciated. I would ask that replies be posted to
the newsgroup; the email referenced in this message is dead.

Thanks again,
David<intrepid_dw@.hotmail.com> wrote in message
news:1111166461.577036.179350@.l41g2000cwc.googlegr oups.com...
> Hi, all.
> I'm trying to become smarter about the use of the FOR XML clause in SQL
> Server. There's one question I'd like to ask that I've not found
> directly answered elsewhere, probably due to my own inaccurate or
> feeble (or both) searching, so I thought I'd ask the good folks here
> for a little information if I may.
> I've played with the FOR XML AUTO, ELEMENTS variation of the XML
> capability, and it is marvelous for what I would call "cleanly"
> hierarchical data, and by that I naively mean always one-to-many
> relationships.

<snip
I don't have an answer myself, but you might get a better response in
microsoft.public.sqlserver.xml

Simon|||(intrepid_dw@.hotmail.com) writes:
> The data I'm trying to model has, at a basic level, several one-to-many
> relationships, eg Parent has many children of type X, and many children
> of type Y. X and Y, themselves, are unrelated. When I write the query
> to dump this data, however, SQL Server tries to wrap Y records as
> children of X records, which is not correct. Another way of thinking
> about it might be a list of PERSONS, and there is a BOOKS table of
> favorite books for each person, and a table of favorite TV shows for
> each person. BOOKS and TV are unrelated.

I'm by no means an expert in XML, but I would guess that you need to
use FOR XML EXPLICIT in this case. Below is an example for your situation.
I should add that I mainly made this example for my own exercise, so
this may not be the "proper" way to write it.

SELECT 1 as Tag,
NULL as Parent,
OrderID as [Order!1!OrderID],
NULL as [Customer!2!CustomerID!element],
NULL as [Customer!2!CompanyName!element],
NULL as [Customer!2!City!element],
NULL as [Employee!3!FirstName!element],
NULL as [Employee!3!LastName!element]
FROM Orders
WHERE OrderID BETWEEN 11000 AND 11020
UNION ALL
select 2, 1,
Orders.OrderID, c.CustomerID, c.CompanyName, c.City, NULL, NULL
from Orders
join Customers c ON Orders.CustomerID = c.CustomerID
WHERE Orders.OrderID BETWEEN 11000 AND 11020
UNION ALL
select 3, 1, o.OrderID, NULL, NULL, NULL, e.FirstName, e.LastName
from Orders o
join Employees e ON o.EmployeeID = e.EmployeeID
WHERE o.OrderID BETWEEN 11000 AND 11020
ORDER BY [Order!1!OrderID], Tag
FOR XML EXPLICIT

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Erland:

The more I study this, the more I think you're right on the money. I
suspected that the problem was at either end of the spectrum; either I
wrote the query horribly wrong to begin with, and was missing something
obvious, or I needed to use the EXPLICIT alternative and the universal
table. Unfortunately, the universal table and query that would be
necessary for the data I'm actually modeling would be HUGE and just
about incomprehensible.

I think what I'm going to do is to design queries to return the "pure"
one-to-many relationships, and then merge the resultant XML into a
larger file. That's not at all complicated and strikes me as a
substantially smarter alternative than trying to write the ELEMENTS
version of this query.

As an irrelevant aside, its interesting to design an XML layout for
existing data because it out almost reminds me of designing a grammar,
eg decompositions, generations of repetitive sections, etc.

Thanks for your assistance, Erland!

-David

Erland Sommarskog wrote:
> (intrepid_dw@.hotmail.com) writes:
> > The data I'm trying to model has, at a basic level, several
one-to-many
> > relationships, eg Parent has many children of type X, and many
children
> > of type Y. X and Y, themselves, are unrelated. When I write the
query
> > to dump this data, however, SQL Server tries to wrap Y records as
> > children of X records, which is not correct. Another way of
thinking
> > about it might be a list of PERSONS, and there is a BOOKS table of
> > favorite books for each person, and a table of favorite TV shows
for
> > each person. BOOKS and TV are unrelated.
> I'm by no means an expert in XML, but I would guess that you need to
> use FOR XML EXPLICIT in this case. Below is an example for your
situation.
> I should add that I mainly made this example for my own exercise, so
> this may not be the "proper" way to write it.
> SELECT 1 as Tag,
> NULL as Parent,
> OrderID as [Order!1!OrderID],
> NULL as [Customer!2!CustomerID!element],
> NULL as [Customer!2!CompanyName!element],
> NULL as [Customer!2!City!element],
> NULL as [Employee!3!FirstName!element],
> NULL as [Employee!3!LastName!element]
> FROM Orders
> WHERE OrderID BETWEEN 11000 AND 11020
> UNION ALL
> select 2, 1,
> Orders.OrderID, c.CustomerID, c.CompanyName, c.City, NULL,
NULL
> from Orders
> join Customers c ON Orders.CustomerID = c.CustomerID
> WHERE Orders.OrderID BETWEEN 11000 AND 11020
> UNION ALL
> select 3, 1, o.OrderID, NULL, NULL, NULL, e.FirstName, e.LastName
> from Orders o
> join Employees e ON o.EmployeeID = e.EmployeeID
> WHERE o.OrderID BETWEEN 11000 AND 11020
> ORDER BY [Order!1!OrderID], Tag
> FOR XML EXPLICIT
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server SP3 at
> http://www.microsoft.com/sql/techin.../2000/books.asp

Question on For XML clause

Hi All,
I have the following three tables . Using FOR XML clause I am getting
result as nested elements. Please let me know if there is anyway of getting
output as shown.
Createtable #Loan(LoanNumint
)
Createtable #Borrower(LoanNumint
,FirstNamevarchar(50)
,LastNamevarchar(50)
)
Createtable #LoanFee (LoanNumint
,LoanFeeNamevarchar(20)
,LoanFeeAmtreal
)
INSERT#LoanVALUES(12345)
INSERT#Borrower VALUES(12345,'Bill', 'Gates')
INSERT#LoanFee VALUES(12345,'Processing Fees', 100.00)
SELECTLoan.LoanNum
,Borrower.FirstName
,Borrower.LastName
,LoanFee.LoanFeeName
,LoanFee.LoanFeeAmt
FROM#Loan Loan (NOLOCK)
JOIN#Borrower Borrower (NOLOCK) ON Borrower.LoanNum = Loan.LoanNum
JOIN#LoanFee LoanFee (NOLOCK) ON LoanFee.LoanNum = Loan.LoanNum
FOR XML AUTO
DROP TABLE #Loan
DROP TABLE #Borrower
DROP TABLE #LoanFee
Current Nested Output :
<Loan LoanNum="12345">
<Borrower FirstName="Bill" LastName="Gates">
<LoanFee LoanFeeName="Processing Fees" LoanFeeAmt="1.0000000e+002"/>
</Borrower>
</Loan>
Expected Output where LoanFee is child of Loan not Borrower:
<Loan LoanNum="12345">
<Borrower FirstName="Bill" LastName="Gates" />
<LoanFee LoanFeeName="Processing Fees" LoanFeeAmt="1.0000000e+002"/>
</Loan>
Thank You
Srinivas
"Srinivas" <Srinivas@.discussions.microsoft.com> wrote in message
news:BC84DD57-3C02-4673-8B04-1A24823F7277@.microsoft.com...
> Hi All,
> I have the following three tables . Using FOR XML clause I am
> getting
> result as nested elements. Please let me know if there is anyway of
> getting
> output as shown.
You will need to use FOR XML EXPLICIT instead of AUTO to get the results you
want. The auto mode nests elements.
Bryant
|||Thank You
"Bryant Likes" wrote:

> "Srinivas" <Srinivas@.discussions.microsoft.com> wrote in message
> news:BC84DD57-3C02-4673-8B04-1A24823F7277@.microsoft.com...
> You will need to use FOR XML EXPLICIT instead of AUTO to get the results you
> want. The auto mode nests elements.
> --
> Bryant
>
>