Friday, March 9, 2012

how to limits recors from a UNION query

I use SQL2000 and I have a query like this:
select * from TabA where 'somecondition'
UNION
select * from TabB where 'somecondition'
order by 'somefield'
I need to limit maximun number of records from this query; problem is that
maybe query A get a lot of records and query B get few records: if i put a
TOP clause in every query i don't reach my purpose. Is there a way to put a
globally TOP clause?How about :
SELECT TOP 100 * FROM
(SELECT * FROM TabA WHERE 'somecondition'
UNION (ALL?)
SELECT * FROM TabB WHERE 'somecondition
ORDER BY 'whatever) AS DerivedTable
Performance? That is another question, isn't it?
RLF
"StefanoMaind" <StefanoMaind@.discussions.microsoft.com> wrote in message
news:17A0C91D-5374-4E71-8C13-3D0BCE406D6C@.microsoft.com...
>I use SQL2000 and I have a query like this:
> select * from TabA where 'somecondition'
> UNION
> select * from TabB where 'somecondition'
> order by 'somefield'
> I need to limit maximun number of records from this query; problem is that
> maybe query A get a lot of records and query B get few records: if i put a
> TOP clause in every query i don't reach my purpose. Is there a way to put
> a
> globally TOP clause?
>|||SELECT TOP 10 col1, col2, ...
FROM
(
select col1, col2, ... from TabA where 'somecondition'
UNION
select col1, col2, ... from TabB where 'somecondition'
) AS i
order by 'somefield'
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"StefanoMaind" <StefanoMaind@.discussions.microsoft.com> wrote in message
news:17A0C91D-5374-4E71-8C13-3D0BCE406D6C@.microsoft.com...
>I use SQL2000 and I have a query like this:
> select * from TabA where 'somecondition'
> UNION
> select * from TabB where 'somecondition'
> order by 'somefield'
> I need to limit maximun number of records from this query; problem is that
> maybe query A get a lot of records and query B get few records: if i put a
> TOP clause in every query i don't reach my purpose. Is there a way to put
a
> globally TOP clause?
>|||Thanks to all
"Tibor Karaszi" wrote:

> SELECT TOP 10 col1, col2, ...
> FROM
> (
> select col1, col2, ... from TabA where 'somecondition'
> UNION
> select col1, col2, ... from TabB where 'somecondition'
> ) AS i
> order by 'somefield'
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
> Blog: http://solidqualitylearning.com/blogs/tibor/
>
> "StefanoMaind" <StefanoMaind@.discussions.microsoft.com> wrote in message
> news:17A0C91D-5374-4E71-8C13-3D0BCE406D6C@.microsoft.com...
>

No comments:

Post a Comment