Showing posts with label query. Show all posts
Showing posts with label query. Show all posts

Wednesday, March 28, 2012

Increase # of chars Query Editor when looking at large varchar field

How can I increase the # of chars so that when I copy a varchar(5500) field from Query Editor back into my Query pane, it displays all the characters, and doesn't cut it off?That is a limitation of the query windows.You will have to navigate through the menu Tools > Options > Query results > Result to text > Maximum numbers of characters displayed in one rows (<- increase this here)

HTH, Jens K. Suessmeyer.

http://www.wsqlserver2005.de|||Thank you, I know I increased that, but was looking at a record which only had a short length of chars to begin with so I wasn't seeing that the increase was actually working but good to know I was in the right place at least. Thanks!sql

Incorrect week number with DATENAME in localized query

Hi,

I'm trying to use the DATENAME function to get a correct Dutch week number, but the DATENAME function seems not to return a localized week number. This is how I have tested it:

-- Set language to English
SET LANGUAGE us_English

-- Declare to dates 12/30/2006 and 12/31/2006
DECLARE @.Dec30 AS DATETIME SET @.Dec30 = CONVERT(DateTime, '2006-12-30')
DECLARE @.Dec31 AS DATETIME SET @.Dec31 = CONVERT(DateTime, '2006-12-31')

-- Return information about the declared dates in English
SELECT @.Dec30 as date1, DATENAME(week, @.Dec30) as week1, DATENAME(weekday, @.Dec30) as day1,
@.Dec31 as date2, DATENAME(week, @.Dec31) as week2, DATENAME(weekday, @.Dec31) as day2

-- Set language to Dutch
SET LANGUAGE Dutch

-- Return information about the declared dates in Dutch
SELECT @.Dec30 as date1, DATENAME(week, @.Dec30) as week1, DATENAME(weekday, @.Dec30) as day1,
@.Dec31 as date2, DATENAME(week, @.Dec31) as week2, DATENAME(weekday, @.Dec31) as day2

In both the English and Dutch results Saturday (12/30/2006) has week number 52 and Sunday (12/31/2006) has week number 53, but this is incorrect for the Dutch language. Sunday should also have week number 52, because the week starts on Monday in The Netherlands.

What am I doing wrong here and how can I get the correct localized week numbers from SQL Server? (I'm using SQL Server 2000 + SP4)

Thanks in advance.

SET Language is used configure the following options, DateFormat, DateFirst, Names of the Month & Names of the Days. So your in the rite direction to get your result..

BUT,

Unfortuantlly SQL Server won't help you to get the proper Week Number. Bcs they are not following ISO standard as you think. The Week 1 always = 1 - jan -any year. So sometimes you will get wrong week number.

The best approach to get the week number is use the custom function to get the week number.

Create Function dbo.MyWeekNo(@.dateFirst int, @.DateValue as DateTime) Returns Int
As
Begin
Declare @.Date as Datetime
declare @.Date2 as Datetime
Declare @.Week as int
Select @.Date = Convert(Varchar,Year(@.DateValue)) + '-01-01', @.Date2=DateAdd(DD,-1,@.Date)

Select @.Week = Case When WeekNo=0 Then dbo.MyWeekNo(@.dateFirst,@.Date2) Else WeekNo End
From
(
Select
Case When DatePart(W,@.Date) >= @.dateFirst Then DatePart(WW,@.DateValue) -1
Else DatePart(WW,@.DateValue) End WeekNo
) as Weeks

Return @.Week;
End

|||

Hi ManiD,

Your function is very close to the function I'm using for years now:

CREATE FUNCTION dbo.DutchWeek(@.DATE AS DateTime) RETURNS Int AS
BEGIN
IF @.DATE IS NULL RETURN NULL;

DECLARE @.JANFIRST AS DateTime
DECLARE @.WEEKDAY AS Int
DECLARE @.DAY AS Int
DECLARE @.DAYOFYEAR AS Int
DECLARE @.WEEKNUMBER AS Int

-- Get Januari the first of the year of @.DATE
SET @.JANFIRST = CONVERT(datetime, '1/1/' + CONVERT(varchar, YEAR(@.DATE)))

-- Calculate the number of the day where 0 = Monday, 1 = Tuesday, etc...
SET @.WEEKDAY = CONVERT(Int, @.JANFIRST) % 7

-- Calculate the (zero-bases) day number (0..265)
SET @.DAYOFYEAR = CONVERT(integer, @.DATE - @.JANFIRST)
-- Calculate the dutch week number
SET @.WEEKNUMBER = (@.DAYOFYEAR + @.WEEKDAY) / 7 +
CASE WHEN @.WEEKDAY > 3 THEN 0 ELSE 1 END

-- When week number is 0, get the weeknumber of the last week of the
-- previous year
IF @.WEEKNUMBER = 0
SET @.WEEKNUMBER = dbo.DutchWeek('12/31/' +
CONVERT(varchar, YEAR(@.DATE)-1));
RETURN @.WEEKNUMBER;
END

I use this function for years, but always had the feeling SQL Server should do this for me. But this is not the case, is it?

Incorrect use of the xml data type method ''modify''. A non-mutator method is expected in th

Hi,

I'm getting an error when I'm executing the follwing query in SQL Server 2005

declare @.xml xml

set @.xml = '<ROOT>

<Customer CustomerID="VINET" ContactName="Paul Henriot">

<Order OrderID="10248" CustomerID="VINET" EmployeeID="5"

OrderDate="1996-07-04T00:00:00">

<OrderDetail ProductID="11" Quantity="12"/>

<OrderDetail ProductID="42" Quantity="10"/>

</Order>

</Customer>

<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">

<Order OrderID="10283" CustomerID="LILAS" EmployeeID="3"

OrderDate="1996-08-16T00:00:00">

<OrderDetail ProductID="72" Quantity="3"/>

</Order>

</Customer>

</ROOT>'

if @.xml.exist('//Order[OrderID="10283"]')=0

begin

set @.xml = @.xml.modify('insert <Order OrderID="10284" CustomerID="LILAS" EmployeeID="3"

OrderDate="1996-08-16T00:00:00"></Order> after //Order[@.OrderID="10283"]')

select @.xml

end

The error is

Incorrect use of the xml data type method 'modify'. A non-mutator method is expected in this context.

Please give me the answare

Regards,

Koustav

Here is a corrected, working version that simply uses SET @.x.modify:

Code Snippet

declare @.xml xml

set @.xml = '<ROOT>

<Customer CustomerID="VINET" ContactName="Paul Henriot">

<Order OrderID="10248" CustomerID="VINET" EmployeeID="5"

OrderDate="1996-07-04T00:00:00">

<OrderDetail ProductID="11" Quantity="12"/>

<OrderDetail ProductID="42" Quantity="10"/>

</Order>

</Customer>

<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">

<Order OrderID="10283" CustomerID="LILAS" EmployeeID="3"

OrderDate="1996-08-16T00:00:00">

<OrderDetail ProductID="72" Quantity="3"/>

</Order>

</Customer>

</ROOT>'

if @.xml.exist('//Order[OrderID="10283"]')=0

begin

set @.xml.modify('

insert <Order OrderID="10284" CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00"></Order> after (//Order[@.OrderID="10283"])[1]')

select @.xml

end

|||

Thanx Martin its now working fine.

I've another query How will I get an attribute's value of a particuler node?

say for example

I've @.xml as xml document and I've find out the following node using xquery

<Order OrderID="10284" CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00"></Order>

Now I want to check if OrderDate >= "1996-08-16" then insert some OrderDetail.

How will I read this OrderDate attribute's value.

Please help me.

Regards,

Koustav

|||

I hope the following example helps:

Code Snippet

DECLARE @.x xml;

SET @.x = '

<Orders>

<Order OrderID="10284" CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00"></Order>

<Order OrderID="10285" CustomerID="Someone" EmployeeID="3" OrderDate="1994-08-16T00:00:00"></Order>

</Orders>';

IF @.x.exist('

/Orders/Order[@.OrderDate >= "1996-08-16T00:00:00"]

') = 1

BEGIN

SET @.x.modify('

insert <OrderDetail Product="Something"/>

into (/Orders/Order[@.OrderDate >= "1996-08-16T00:00:00"])[1]

');

SELECT @.x

END

|||Thanx a lot Martin. It perfectly working.

|||

Continuing the above example I'm facing anaother problem.

Instead of insert xml node I'm trying to replace an attribute's value. I've written

if @.xml.exist('/Customer/Order[@.OrderID="10283"]')=0

begin

--set @.xml.modify('insert <Order OrderID="10284" CustomerID="LILAS" EmployeeID="3"

-- OrderDate="1996-08-16T00:00:00"></Order> after (//Order[@.OrderID="10283"])[1]')

set @.xml.modify('declare namespace ns="http://myOrder";

replace value of (//nsSurpriserder[@.OrderID="10283"]/OrderDetail/@.Quantity)[1] with 4')

select @.xml

end

The XML is untyped xml. There are no such schema named "myOrder" but if I'm not giving the line "declare namespace ns='http://myOrder';" its throwing error.

Now the problem is. this query is executing but the value dose not replace.

Please give me the solution.

|||

The following sample code works flawlessly for me, the Quantity attribute value is changed from 3 to 4:

Code Snippet

DECLARE @.xml xml;

SET @.xml = '<Customer>

<Order OrderID="10283">

<OrderDetail Quantity="3"/>

</Order>

</Customer>';

IF @.xml.exist('/Customer/Order[@.OrderID="10283"]') = 1

BEGIN

SET @.xml.modify('

replace value of (//Order[@.OrderID="10283"]/OrderDetail/@.Quantity)[1] with 4

');

END;

SELECT @.xml;

|||

Thank you Martin, I don't know why it was not running in my environment. But fortunatly now it aslo running in my machine. Thanks for your help.

Martine, I'm also facing another problem.

...

...

declare @.CID varchar(10)

DECLARE C1 CURSOR FOR SELECT ID FROM select customerID from customer

OPEN C1;

FETCH NEXT FROM C1 into @.CID

WHILE @.@.FETCH_STATUS = 0

BEGIN

set @.queryString = 'for $cust in //Customer where $cust/@.CustmerID = "' + @.CID + '" return $cust'

--set @.detail = @.xml.query('for $cust in //Customer where $cust/@.CustmerID = "' + @.CID + '" return $cust')

set @.detail = @.xml.query(@.queryString)

select @.detail

select @.queryString

FETCH NEXT FROM C1 into @.CID

END

....

...

Its showing an error

The argument 1 of the xml data type method "query" must be a string literal.

That means query() can't execute a string veriable. But I've to meet this type of requirment. From above XML I want to read each node then doing some processing into subnodes and then put the value into a table. So first I've to process 1st customer node and its child nodes then shift to 2nd customer and so on.

Please help me how will I proceed.

|||

You can use sql:variable as follows:

Code Snippet

DECLARE @.CID nvarchar(10);

SET @.CID = '1234';

DECLARE @.xml xml;

SET @.xml = '<root>

<Customer CustomerId="1233"/>

<Customer CustomerId="1234"/>

</root>'

SELECT @.xml.query('

for $c in root/Customer

where $c/@.CustomerId = sql:variable("@.CID")

return $c

');

|||

Hi,

I have problem in replacing set of elements with text.

declare @.dtToday datetime

, @.input xml

set @.dtToday = getdate()

-- here is my input XML

set @.input = '<TsfDesc>

<physical_to_loc>1000004</physical_to_loc>

<to_loc_type>S</to_loc_type>

<pick_not_before_date>

<year>2001</year>

<month>03</month>

<day>09</day>

<hour>00</hour>

<minute>00</minute>

<second>00</second>

</pick_not_before_date>

<to_loc_type>S</to_loc_type>

</TsfDesc>'

I would like to get the output as shown below

'<TsfDesc>

<physical_to_loc>1000004</physical_to_loc>

<to_loc_type>S</to_loc_type>

<pick_not_before_date>03/09/2001 00:00:00

</pick_not_before_date>

<to_loc_type>S</to_loc_type>

</TsfDesc>'

would you please help me?

Thanks in advance.

Meeran.

|||

Here is a solution using several steps:

Code Snippet

DECLARE @.input xml;

set @.input = '<TsfDesc>

<physical_to_loc>1000004</physical_to_loc>

<to_loc_type>S</to_loc_type>

<pick_not_before_date>

<year>2001</year>

<month>03</month>

<day>09</day>

<hour>00</hour>

<minute>00</minute>

<second>00</second>

</pick_not_before_date>

<to_loc_type>S</to_loc_type>

</TsfDesc>';

DECLARE @.date nvarchar(19);

SET @.date = @.input.value('

concat((TsfDesc/pick_not_before_date/day)[1], "/", (TsfDesc/pick_not_before_date/month)[1], "/", (TsfDesc/pick_not_before_date/year)[1], " ", (TsfDesc/pick_not_before_date/hour)[1], ":", (TsfDesc/pick_not_before_date/minute)[1], ":", (TsfDesc/pick_not_before_date/second)[1])

', 'nvarchar(19)');

SET @.input.modify('

delete TsfDesc/pick_not_before_date/node()

')

SET @.input.modify('

insert text{sql:variable("@.date")}

into (TsfDesc/pick_not_before_date)[1]

');

SELECT @.input;

|||

Thanks a lot Martin, for your prompt response.

Incorrect syntax with Declare

Good morning
I hope this will be a simple one, but I am trying to write a view to query my SQL server database, setting a variable using "declare". The code runs fine and returns a number of records, but when I try to save it, it comes up with "Incorrect syntax near the keyword DECLARE", and will not save. I am a bit of a novice when it comes to SQL, but I don't understand why it runs, but won't save. Here is my variable:
DECLARE @.ANCHORDATE AS DATETIME
SET @.ANCHORDATE = CASE WHEN datepart(mm, getdate()) BETWEEN 4 AND 9 THEN dateadd(mm, 3, DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)) ELSE dateadd(mm, - 9,
DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)) END

Thanks for any help.I am not 100% sure but you can try not to use DECLARE and try and save it. Let me know if it helps.|||I have replaced all the instances of the variable with the actual definition, and the view runs and saves fine. I was hoping to be able to keep it simple by not having to type in the variable definition each time. I don't understand why it can run, but saving it returns an error.

Monday, March 26, 2012

Incorrect syntax near the keyword 'UNION'. ??

Hi,
Why does this query give this error?
SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
tblCampaigns.Campaign
WHERE (Number = '+32479990284') OR (Number = '0479990284')
ORDER BY SendDate DESC
UNION
SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
tblCampaigns.Campaign
WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND (SendDate
> DATEADD(hh, 48 ,GETDATE() ))
Error:
Server: Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'UNION'.
What I need to do is Select all the records (tblSMS) with SendDate from the
last 48 hours, and I have also to select the Last one (in case it isn't yet
in the last 48 hours).
Does anybody knwos what goes wrong?
If I try the two query's separetly they work fine...
Thanks a lot,
Pieter
You can't have an ORDER BY before the UNION. Put the ORDER BY after the
final SELECT.
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>
|||An Order By can only be used to determine the output of the entire result
set when you use
UNION. You can't use it with the individual queries.
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>
|||By the way, that will totally distroy your TOP 1 logic... but here's a very
simple solution:
SELECT *
FROM
(SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
tblCampaigns.Campaign
WHERE (Number = '+32479990284') OR (Number = '0479990284')
ORDER BY SendDate DESC) x
UNION
SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
tblCampaigns.Campaign
WHERE ((Number = '+32479990284') OR (Number = '0479990284'))
AND (SendDate > DATEADD(hh, 48 ,GETDATE() ))
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>
|||You can't put ORDER BY inside individual parts of the UNION. Move it to the
end...
http://www.aspfaq.com/
(Reverse address to reply.)
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>
|||Thansk guys!! It works fine now!
"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:uqB6AMzxEHA.2036@.TK2MSFTNGP12.phx.gbl...
> By the way, that will totally distroy your TOP 1 logic... but here's a
very
> simple solution:
> SELECT *
> FROM
> (SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC) x
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284'))
> AND (SendDate > DATEADD(hh, 48 ,GETDATE() ))
> --
> Adam Machanic
> SQL Server MVP
> http://www.sqljunkies.com/weblog/amachanic
> --
>
> "DraguVaso" <pietercoucke@.hotmail.com> wrote in message
> news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> (SendDate
> the
> yet
>

Incorrect syntax near the keyword 'UNION'. ??

Hi,
Why does this query give this error?
SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
tblCampaigns.Campaign
WHERE (Number = '+32479990284') OR (Number = '0479990284')
ORDER BY SendDate DESC
UNION
SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
tblCampaigns.Campaign
WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND (SendDate
> DATEADD(hh, 48 ,GETDATE() ))
Error:
Server: Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'UNION'.
What I need to do is Select all the records (tblSMS) with SendDate from the
last 48 hours, and I have also to select the Last one (in case it isn't yet
in the last 48 hours).
Does anybody knwos what goes wrong?
If I try the two query's separetly they work fine...
Thanks a lot,
PieterYou can't have an ORDER BY before the UNION. Put the ORDER BY after the
final SELECT.
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>|||An Order By can only be used to determine the output of the entire result
set when you use
UNION. You can't use it with the individual queries.
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>|||By the way, that will totally distroy your TOP 1 logic... but here's a very
simple solution:
SELECT *
FROM
(SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
tblCampaigns.Campaign
WHERE (Number = '+32479990284') OR (Number = '0479990284')
ORDER BY SendDate DESC) x
UNION
SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
tblCampaigns.Campaign
WHERE ((Number = '+32479990284') OR (Number = '0479990284'))
AND (SendDate > DATEADD(hh, 48 ,GETDATE() ))
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>|||You can't put ORDER BY inside individual parts of the UNION. Move it to the
end...
http://www.aspfaq.com/
(Reverse address to reply.)
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>|||Thansk guys!! It works fine now!
"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:uqB6AMzxEHA.2036@.TK2MSFTNGP12.phx.gbl...
> By the way, that will totally distroy your TOP 1 logic... but here's a
very
> simple solution:
> SELECT *
> FROM
> (SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC) x
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =
> tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284'))
> AND (SendDate > DATEADD(hh, 48 ,GETDATE() ))
> --
> Adam Machanic
> SQL Server MVP
> http://www.sqljunkies.com/weblog/amachanic
> --
>
> "DraguVaso" <pietercoucke@.hotmail.com> wrote in message
> news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> (SendDate
> the
> yet
>sql

Incorrect syntax near the keyword 'UNION'. ??

Hi,
Why does this query give this error?
SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign = tblCampaigns.Campaign
WHERE (Number = '+32479990284') OR (Number = '0479990284')
ORDER BY SendDate DESC
UNION
SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign = tblCampaigns.Campaign
WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND (SendDate
> DATEADD(hh, 48 ,GETDATE() ))
Error:
Server: Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'UNION'.
What I need to do is Select all the records (tblSMS) with SendDate from the
last 48 hours, and I have also to select the Last one (in case it isn't yet
in the last 48 hours).
Does anybody knwos what goes wrong?
If I try the two query's separetly they work fine...
Thanks a lot,
PieterYou can't have an ORDER BY before the UNION. Put the ORDER BY after the
final SELECT.
--
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> > DATEADD(hh, 48 ,GETDATE() ))
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>|||An Order By can only be used to determine the output of the entire result
set when you use
UNION. You can't use it with the individual queries.
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> > DATEADD(hh, 48 ,GETDATE() ))
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>|||By the way, that will totally distroy your TOP 1 logic... but here's a very
simple solution:
SELECT *
FROM
(SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign = tblCampaigns.Campaign
WHERE (Number = '+32479990284') OR (Number = '0479990284')
ORDER BY SendDate DESC) x
UNION
SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign =tblCampaigns.Campaign
WHERE ((Number = '+32479990284') OR (Number = '0479990284'))
AND (SendDate > DATEADD(hh, 48 ,GETDATE() ))
--
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> > DATEADD(hh, 48 ,GETDATE() ))
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>|||You can't put ORDER BY inside individual parts of the UNION. Move it to the
end...
--
http://www.aspfaq.com/
(Reverse address to reply.)
"DraguVaso" <pietercoucke@.hotmail.com> wrote in message
news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> Hi,
> Why does this query give this error?
> SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
(SendDate
> > DATEADD(hh, 48 ,GETDATE() ))
> Error:
> Server: Msg 156, Level 15, State 1, Line 5
> Incorrect syntax near the keyword 'UNION'.
> What I need to do is Select all the records (tblSMS) with SendDate from
the
> last 48 hours, and I have also to select the Last one (in case it isn't
yet
> in the last 48 hours).
> Does anybody knwos what goes wrong?
> If I try the two query's separetly they work fine...
> Thanks a lot,
> Pieter
>|||Thansk guys!! It works fine now!
"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:uqB6AMzxEHA.2036@.TK2MSFTNGP12.phx.gbl...
> By the way, that will totally distroy your TOP 1 logic... but here's a
very
> simple solution:
> SELECT *
> FROM
> (SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE (Number = '+32479990284') OR (Number = '0479990284')
> ORDER BY SendDate DESC) x
> UNION
> SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => tblCampaigns.Campaign
> WHERE ((Number = '+32479990284') OR (Number = '0479990284'))
> AND (SendDate > DATEADD(hh, 48 ,GETDATE() ))
> --
> Adam Machanic
> SQL Server MVP
> http://www.sqljunkies.com/weblog/amachanic
> --
>
> "DraguVaso" <pietercoucke@.hotmail.com> wrote in message
> news:u1zDVHzxEHA.4040@.TK2MSFTNGP11.phx.gbl...
> > Hi,
> >
> > Why does this query give this error?
> > SELECT TOP 1 tblSMS.*, tblCampaigns.Mail
> > FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => > tblCampaigns.Campaign
> > WHERE (Number = '+32479990284') OR (Number = '0479990284')
> > ORDER BY SendDate DESC
> > UNION
> > SELECT DISTINCT tblSMS.*, tblCampaigns.Mail
> > FROM tblSMS LEFT JOIN tblCampaigns ON tblSms.Campaign => > tblCampaigns.Campaign
> > WHERE ((Number = '+32479990284') OR (Number = '0479990284')) AND
> (SendDate
> > > DATEADD(hh, 48 ,GETDATE() ))
> >
> > Error:
> > Server: Msg 156, Level 15, State 1, Line 5
> > Incorrect syntax near the keyword 'UNION'.
> >
> > What I need to do is Select all the records (tblSMS) with SendDate from
> the
> > last 48 hours, and I have also to select the Last one (in case it isn't
> yet
> > in the last 48 hours).
> >
> > Does anybody knwos what goes wrong?
> >
> > If I try the two query's separetly they work fine...
> >
> > Thanks a lot,
> >
> > Pieter
> >
> >
>

Incorrect syntax near the keyword SELECT

Hello, I have the following query. When I run the query I get the following error message: "Incorrect syntax near keyword SELECT"

----------------
SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY DateAdded) AS rownum, * FROM

SELECT TOP (100) PERCENT Videos.VideoId, Videos.UserId, Videos.UserName, Videos.Title, Videos.Description, Videos.Tags, Videos.VideoLength, Videos.TimesHeard,
Videos.ImageURL, Videos.RecType, Videos.Language, Videos.Category, Videos.DateAdded, Videos.RewardProgram, Videos.EditorChoice, TB2.hits
FROM Videos LEFT OUTER JOIN
(SELECT TOP (100) PERCENT VideoId, COUNT(*) AS hits
FROM (SELECT TOP (100) PERCENT UserId, VideoId, COUNT(*) AS cnt1
FROM Hits
GROUP BY VideoId, UserId) AS TB1
GROUP BY VideoId) AS TB2 ON Videos.VideoId = TB2.VideoId
ORDER BY TB2.hits DESC
) AS T1
WHERE rownum <= 5

-------------

If I run the query that is in BOLD as:

SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY DateAdded) AS rownum, * FROM Videos) AS T1 WHERE rownum <=5

the query runs just fine. Also if I run the query that is NOT bold (above), it also runs fine. What can I do to run them both together as seen above?


Thank in advance,

Louis

Try this:

SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY DateAdded) AS rownum, * FROM(SELECT TOP (100) PERCENT Videos.VideoId, Videos.UserId, Videos.UserName, Videos.Title, Videos.Description, Videos.Tags, Videos.VideoLength, Videos.TimesHeard,
Videos.ImageURL, Videos.RecType, Videos.Language, Videos.Category, Videos.DateAdded, Videos.RewardProgram, Videos.EditorChoice, TB2.hits
FROM Videos LEFT OUTER JOIN
(SELECT TOP (100) PERCENT VideoId, COUNT(*) AS hits
FROM (SELECT TOP (100) PERCENT UserId, VideoId, COUNT(*) AS cnt1
FROM Hits
GROUP BY VideoId, UserId) AS TB1
GROUP BY VideoId) AS TB2 ON Videos.VideoId = TB2.VideoId
ORDER BY TB2.hits DESC

)
) AS T1
WHERE rownum <= 5

|||

Thanks Limno, but I had tried that before and I get this error:

Incorrect syntax near ')'

I don't understand why

Louis

|||

Here is a working one:

SELECT*FROM(SELECT ROW_NUMBER()OVER(ORDERBY DateAdded)AS rownum,*FROM(SELECTTOP(100)PERCENT Videos.VideoId, Videos.UserId, Videos.UserName, Videos.Title, Videos.Description, Videos.Tags, Videos.VideoLength, Videos.TimesHeard,

Videos.ImageURL, Videos.RecType, Videos.Language, Videos.Category, Videos.DateAdded, Videos.RewardProgram, Videos.EditorChoice, TB2.hits

FROM VideosLEFTOUTERJOIN

(SELECTTOP(100)PERCENT VideoId,COUNT(*)AS hits

FROM(SELECTTOP(100)PERCENT UserId, VideoId,COUNT(*)AS cnt1

FROM Hits

GROUPBY VideoId, UserId)AS TB1

GROUPBY VideoId)AS TB2ON Videos.VideoId= TB2.VideoId

ORDERBY TB2.hitsDESC

)AS T1) AS T2

WHERE rownum<= 5

|||

Thanks Limno, that worked

Louis

Incorrect syntax near the keyword 'CONVERT'

What in the name of all creation is wrong with this query? I just can't seem to find the trouble...

EXEC OppdaterForetak 900000000,'NO NON MOD DUNS Test 1','abcdveien 145','110','OSLO',NULL,'118','OSLO','22222222','22222222',CONVERT(datetime,'2006-07-18 00:00'), 101,'OSLO', 3,'Oslo','AS', 99999,'NB! TESTFORETAK',NULL,NULL,NULL, 345000001,CONVERT(datetime,'2006-07-17 00:00'),CONVERT(datetime,'2006-07-19 00:00'),'A',NULL,'Daglig leder alene.'

You can't use any function when you call the Procedure. It should be predefined.

Here you can use the variable to assign the values then reuse the varibale on the procedure call.

But for your query convertion is not nessasary.. since you are using the valid dateformat..

Code Snippet

EXEC OppdaterForetak 900000000,

'NO NON MOD DUNS Test 1',

'abcdveien 145',

'110',

'OSLO',

NULL,

'118',

'OSLO',

'22222222',

'22222222',

'2006-07-18 00:00:00',

101,

'OSLO',

3,

'Oslo',

'AS',

99999,

'NB! TESTFORETAK',

NULL,

NULL,

NULL,

345000001,

'2006-07-17 00:00:00',

'2006-07-19 00:00:00',

'A',

NULL,

'Daglig leder alene.'

incorrect syntax near LEFT

this is the query im trying to execute in sql server.please let me know what is the error in this

SELECT "PROJECT"."PROJ_NAM", ' ' as dev_name, "PROJECT_FUND"."F_FUND_ID" as fund_id, view_on_watch_list.on_date
FROM LEFT OUTER JOIN view_on_watch_list ON project.proj_id =view_on_watch_list.proj_id , "PROJECT_FUND" LEFT OUTER JOIN "FUND" ON "PROJECT_FUND"."F_FUND_ID" = "FUND"."FUND_ID" AND project.proj_id = project_fund.f_proj_id , "PROJECT" WHERE (("PROJECT"."PROJ_ID" = 1))
select "PROJECT"."PROJ_ID", ' ' AS DEV_TYPE from PROJECTFROM LEFT OUTER JOIN
Enter Table_Name after "FROM" clause...

project.proj_id = project_fund.f_proj_id , "PROJECT" WHERE (("PROJECT"."PROJ_ID" = @.proj_id))
select "PROJECT"."PROJ_ID", ' ' AS DEV_TYPE from PROJECT
I didn't get what you want to do... Post your table structure, data & your requirement.|||actually im a beginner in MSSQL.im not aware of this LEFT OUTER JOIN syntax.
i tried with placing table name after 'LEFT' ,below error was thrown

[Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Tables or functions 'project' and 'PROJECT' have the same exposed names. Use correlation names to distinguish them.|||Wel Come :)

Before you use query in application code, run & check it using SQL Query Analyzer.

Develop query step by step i.e. don't write entire query at once but create 1st then 2nd phrase etc...

Spend some time to learn, you can refer SELECT syntax in Books OnLine from SQL Query Analyzer.|||Hi

If you are just starting you might find this a gentler learning curve:
http://www.w3schools.com/sql/sql_intro.asp

rajeshpatel is spot on - don't write out loads at once - write a small section, run, if it works write some more else refer to the link and correct.

HTH|||thank u rajesh.im familiar with sql's(DDLS and DMLS).please guide me to the correct query for the above one.|||I'm afraid the SQL is so bad it is not possible to tell what you want you want to do. I strongly recommend you read the link and have another stab at writing it. As you come up against problems get back to us with specifics.

If you build up a bit at a time it might be possible to infer what you are actually attempting to do.

Incorrect syntax near LEFT

Hi guys;

I am trying to create a stored procedure in my database with dynamic filter, how ever i cant even let my query work.

When i run my stored procedure i get this errorIncorrect syntax near 'LEFT'

I dnt knw wats wrong with my code.

Please help me...
below is my stored procedure..

Thanks is advance.


ALTER PROCEDURE dbo.GetClassByCustomFilter
@.pcCustomFilterNVARCHAR(500)=''
AS

DECLARE @.sSqlString nvarchar(1024)

SET @.sSqlString = 'SELECT R.cRoomNo, P.cFirstName, P.cLastName, P.cMiddleName, U.cCode AS cSubjectCode, U.cName AS cSubjectName, '
SET @.sSqlString = @.sSqlString + 'U.cDescription AS cSubjectDescription, B.cCode AS cSection, H.cName AS cRecurenceName, C.iClassID, C.iInstructorID, C.iSubjectid, C.iEnrollmentID, '
SET @.sSqlString = @.sSqlString + 'C.iRecordTypeID, C.iBlockSectionID, C.cCode, C.cType, C.iRoomID, C.cRecurrence, CAST(CONVERT(nvarchar, GETDATE(), 1) + '' '' + CONVERT(nvarchar, '
SET @.sSqlString = @.sSqlString + 'C.tStartTime,8) AS datetime) AS tStartTime, CAST(CONVERT(nvarchar, GETDATE(), 1) + '' '' + CONVERT(nvarchar, C.tEndTime,8) AS datetime) '
SET @.sSqlString = @.sSqlString + 'AS tEndTime, C.fUnits, C.nAllowed, C.nMaxAllowed, C.mNotes, C.tCreated, C.tEdited, C.iEditedBy, C.iCreatedby, C.adGUID '
SET @.sSqlString = @.sSqlString + 'FROM dbo.PERSONALINFO P INNER JOIN dbo.INSTRUCTORS I ON P.iPersonalInfoId = I.iPersonalInfoID RIGHT OUTER JOIN '
SET @.sSqlString = @.sSqlString + 'dbo.CLASSES C INNER JOIN dbo.BLOCKSECTIONS B ON C.iBlockSectionID = B.iBlockSectionId INNER JOIN '
SET @.sSqlString = @.sSqlString + 'dbo.SUBJECTS U ON C.iSubjectid = U.iSubjectID LEFT OUTER JOIN '
SET @.sSqlString = @.sSqlString + 'dbo.SCHEDULERECURRENCE H ON C.cRecurrence = H.cRecurrence ON I.iInstructorID = C.iInstructorID LEFT OUTER JOIN '
SET @.sSqlString = @.sSqlString + 'dbo.ROOMS R ON C.iRoomID = R.iRoomId WHERE (C.cType <> ''0'')'

IF LEN(@.pcCustomFilter) > 0

BEGIN
SET@.sSqlString = @.sSqlString + ' AND ' + @.pcCustomFilter
END

EXEC sp_executesql @.sSqlString

Well, thanks for reminding me why I hate complex dynamic SQL strings.

Thisa line is causing you problems:

SET @.sSqlString = @.sSqlString + 'dbo.SCHEDULERECURRENCE H ON C.cRecurrence = H.cRecurrence ON I.iInstructorID = C.iInstructorID LEFT OUTER JOIN '

Note the:ON C.cRecurrence = H.cRecurrenceON I.iInstructorID = C.iInstructorID (two ON clauses for a single JOIN clause).|||Thanks for the reply .

The Query is correct.

I get this error because the lenght of the variable@.sSqlString is only 1024 but my query string is longer than that.

Regards|||Well, be that as it may, having to ON statements for a single JOIN clause will give you a syntax error...|||Of course it will. But the SQL statement below has 6JOIN and 6ON.

enewe thanks 4 the time.

Regards.|||The following, cut and pasted from you original post, is what I'm referencing:


SET @.sSqlString = @.sSqlString + 'dbo.SUBJECTS U ON C.iSubjectid = U.iSubjectID LEFT OUTER JOIN '
SET @.sSqlString = @.sSqlString + 'dbo.SCHEDULERECURRENCE H ON C.cRecurrence = H.cRecurrence ON I.iInstructorID = C.iInstructorID LEFT OUTER JOIN '

Note the 'ON C.cRecurrence = H.cRecurrence ON I.iInstructorID = C.iInstructorID' of the second line. That will cause issues.

However, I'm glad you got it working...|||Of course it wont work bcoz its just a part of the statement, not the whole statement. :) jst Kid'N. But I am 101% sure that the SQL Statement below will work because I just copied it from Visual Studio .NET View Designer.

8)

Wednesday, March 21, 2012

Incorrect Results with t-sql Query in SQL Server 2005

I'm seeing some change in behavior for a query in SQL Server 2005 (compared to behavior in SQL Server 2000). The query is as follows:
create table #projects (projectid int) insert into #projects select projectid from tblprojects where istemplate = 0 and projecttemplateid = 365

Select distinct tblProjects.ProjectID
from tblProjects WITH (NOLOCK)
inner join #projects on #projects.projectid = tblprojects.projectid
Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID = tblMilestones.ProjectID
and tblProjects.projectID in (
select projectid
from tblMilestones
where (parent = 683691 AND PrimaryDate between '4/15/2006' and '4/22/2006' )
and enabled = 1 )
This is dynamic SQL generated by the application when a user requests a report with variable parameters. It works fine in SQL Server 2000. It outputs 47 records which is correct.

In SQL Server 2005, for some reason, the DISTINCT keyword is behaving as a TOP operator and outputs just 1 record. (Results of Showplan Text at the end of this post).

If I modify the query even the slightest bit by:
1) Changing "where (parent = 683691 AND PrimaryDate between '4/15/2006' and '4/22/2006' )
and enabled = 1 )"
To " where (parent = 683691 AND PrimaryDate between '4/15/2006' and '4/22/2006' ) )
and enabled = 1 "

2) Changing " Select distinct tblProjects.ProjectID"
To " Select distinct tblProjects.ProjectID+''"

3) Removing the Distinct keyword, storing into a Temp table, then performing a distinct on the temp table

4) Adding: OPTION (FORCE ORDER)

5) OR completely fixing the query (remove redundant loops, etc)

...it works fine (outputs 47 records). It also works if I created new tables (eg. tMilestones instead of tblMilestones) and inserted about 10 records into each and ran the query referencing these new tables.

I reindexed the tables, updated stats, updated usage, ran DBCC FREEPROCCACHE, changed MaxDOP settings...nothing makes the query behave the way it does in SQL Server 2000 without modifying the query/adding the query hint.

Have you come across this? Any ideas on what might be causing the "TOP" operation. (Somewhat resembles the bug mentioned in this article: http://www.kbalertz.com/Feedback_910392.aspx - but this was apparently fixed POST-SQL Server 2000 SP4 - so has it not made it into SQL Server 2005 yet?).

I will appreciate any new insights you might have on this issue.
Thanks much,
Smitha

P.S. Results of Showplan Text:

StmtText

SET STATISTICS PROFILE ON

(1 row(s) affected)

StmtText

Select distinct tblProjects.ProjectID from tblProjects WITH (NOLOCK)
inner join #projects on #projects.projectid = tblprojects.projectid
Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID = tblMilestones.ProjectID
and tblProjects.projectID in (
select tblMilestones.projectid from tblMilestones
where (parent = 683691 AND tblMilestones.PrimaryDate between '4/15/2006' and '4/22/2006' )
and tblMilestones.enabled = 1 )

(1 row(s) affected)

StmtText

|--Stream Aggregate(DEFINE:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID]=ANY([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID])))
|--Nested Loops(Inner Join, OUTER REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
|--Nested Loops(Inner Join, OUTER REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
| |--Filter(WHERE:(CONVERT_IMPLICIT(tinyint,[ExpesiteProductionCopy].[dbo].[tblMilestones].[Enabled],0)=(1)))
| | |--Nested Loops(Inner Join, OUTER REFERENCES:([Uniq1014], [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) OPTIMIZED)
| | |--Merge Join(Inner Join, MERGE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID], [Uniq1014])=([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID], [Uniq1014]), RESIDUAL:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] = [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] AND [Uniq1014] = [Uniq1014]))
| | | |--Sort(ORDER BY:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] ASC, [Uniq1014] ASC))
| | | | |--Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byPrimaryDate]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate] >= '2006-04-15 00:00:00.000' AND [ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate] <= '2006-04-22 00:00:00.000') ORDERED FORWARD)
| | | |--Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byParentID]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[Parent]=(683691)) ORDERED FORWARD)
| | |--Clustered Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] AND [Uniq1014]=[Uniq1014]) LOOKUP ORDERED FORWARD)
| |--Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblProjects].[PK_tblProjects_1]), SEEK:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID]=[ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)
|--Top(TOP EXPRESSION:((1)))
|--Nested Loops(Inner Join)
|--Table Scan(OBJECT:([tempdb].[dbo].[#projects]), WHERE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[tempdb].[dbo].[#projects].[projectid]))
|--Clustered Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)

(15 row(s) affected)

StmtText
--
SET STATISTICS PROFILE OFF

(1 row(s) affected)

It would be great if you reported this at

http://lab.msdn.microsoft.com/productfeedback. If you do,

you are more likely to get the attention of the right

people, and you might find out if this is a known bug, and

if so, what the status is.

Steve Kass

Drew University

Smitha_Expesite@.discussions.microsoft.com wrote:

> I'm seeing some change in behavior for a query in SQL Server 2005

> (compared to behavior in SQL Server 2000). The query is as follows:

>

> create table #projects (projectid int) insert into #projects select

> projectid from tblprojects where istemplate = 0 and projecttemplateid =

> 365

>

> Select distinct tblProjects.ProjectID

> from tblProjects WITH (NOLOCK)

> inner join #projects on #projects.projectid = tblprojects.projectid

> Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID =

> tblMilestones.ProjectID

> and tblProjects.projectID in (

> select projectid

> from tblMilestones b

> where (parent = 683691 AND PrimaryDate between

> '4/15/2006' and '4/22/2006' )

> and enabled = 1 )

>

> This is dynamic SQL generated by the application when a user requests a

> report with variable parameters. It works fine in SQL Server 2000. It

> outputs 47 records which is correct.

>

> In SQL Server 2005, for some reason, the DISTINCT keyword is behaving as

> a TOP operator and outputs just 1 record. (Results of Showplan Text at

> the end of this post).

>

> If I modify the query even the slightest bit by:

> 1) Changing "where (parent = 683691 AND PrimaryDate between '4/15/2006'

> and '4/22/2006' )

> and enabled = 1 )"

> To " where (parent = 683691 AND PrimaryDate between '4/15/2006' and

> '4/22/2006' ) )

> and enabled = 1 "

>

> 2) Changing " Select distinct tblProjects.ProjectID"

> To " Select distinct tblProjects.ProjectID+''"

>

> 3) Removing the Distinct keyword, storing into a Temp table, then

> performing a distinct on the temp table

>

> 4) Adding: OPTION (FORCE ORDER)

>

> 5) OR completely fixing the query (remove redundant loops, etc)

>

> ...it works fine (outputs 47 records). It also works if I created new

> tables (eg. tMilestones instead of tblMilestones) and inserted about 10

> records into each and ran the query referencing these new tables.

>

> I reindexed the tables, updated stats, updated usage, ran DBCC

> FREEPROCCACHE, changed MaxDOP settings...nothing makes the query behave

> the way it does in SQL Server 2000 without modifying the query/adding

> the query hint.

>

> Have you come across this? Any ideas on what might be causing the "TOP"

> operation. (Somewhat resembles the bug mentioned in this article:

> http://www.kbalertz.com/Feedback_910392.aspx - but this was apparently

> fixed POST-SQL Server 2000 SP4 - so has it not made it into SQL Server

> 2005 yet?).

>

> I will appreciate any new insights you might have on this issue.

> Thanks much,

> Smitha

>

>

> P.S. Results of Showplan Text:

>

> StmtText

>

> SET STATISTICS PROFILE ON

>

> (1 row(s) affected)

>

> StmtText

>

>

>

>

>

>

>

> Select distinct tblProjects.ProjectID from tblProjects WITH (NOLOCK)

> inner join #projects on #projects.projectid = tblprojects.projectid

> Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID =

> tblMilestones.ProjectID

> and tblProjects.projectID in (

> select tblMilestones.projectid from tblMilestones

> where (parent = 683691 AND tblMilestones.PrimaryDate between '4/15/2006'

> and '4/22/2006' )

> and tblMilestones.enabled = 1 )

>

> (1 row(s) affected)

>

> StmtText

>

>

>

>

>

>

> |--Stream

> Aggregate(DEFINE:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectI

> D]=ANY([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID])))

> |--Nested Loops(Inner Join, OUTER

> REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))

> |--Nested Loops(Inner Join, OUTER

> REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))

> |

> |--Filter(WHERE:(CONVERT_IMPLICIT(tinyint,[ExpesiteProductionCopy].[dbo]

> .[tblMilestones].[Enabled],0)=(1)))

> | | |--Nested Loops(Inner Join, OUTER

> REFERENCES:([Uniq1014],

> [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) OPTIMIZED)

> | | |--Merge Join(Inner Join,

> MERGE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID],

> [Uniq1014])=([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID],

> [Uniq1014]),

> RESIDUAL:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] =

> [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] AND

> [Uniq1014] = [Uniq1014]))

> | | | |--Sort(ORDER

> BY:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] ASC,

> [Uniq1014] ASC))

> | | | | |--Index

> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byPrimaryDa

> te]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate]

>

>>= '2006-04-15 00:00:00.000' AND

>

> [ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate] <=

> '2006-04-22 00:00:00.000') ORDERED FORWARD)

> | | | |--Index

> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byParentID]

> ),

> SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[Parent]=(683691))

> ORDERED FORWARD)

> | | |--Clustered Index

> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid])

> ,

> SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[Expesi

> teProductionCopy].[dbo].[tblMilestones].[ProjectID] AND

> [Uniq1014]=[Uniq1014]) LOOKUP ORDERED FORWARD)

> | |--Index

> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblProjects].[PK_tblProject

> s_1]),

> SEEK:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID]=[Expesite

> ProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)

> |--Top(TOP EXPRESSION:((1)))

> |--Nested Loops(Inner Join)

> |--Table Scan(OBJECT:([tempdb].[dbo].[#projects]),

> WHERE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[tempd

> b].[dbo].[#projects].[projectid]))

> |--Clustered Index

> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid])

> ,

> SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[Expesi

> teProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)

>

> (15 row(s) affected)

>

> StmtText

> --

> SET STATISTICS PROFILE OFF

>

> (1 row(s) affected)

>

>

>

>

>

>|||OK...I will report it to the Feedback folks. Thanks!|||

The Hotfix that you mentioned (http://www.kbalertz.com/Feedback_910392.aspx) is fixed in SQL Server 2005 RTM, so you may have discovered a new bug in SQL. If so, I would like to fix it. However, I do not have enough information to do that yet.

The first thing I would recommend is to send me a clone of your database. This is a version with no data, but with all the statistics intact (as though the tables were large), so we will get the same plans.

Please contact me for help making the clone.

Marc Friedman

marcfr@.removethispart.microsoft.com

|||Sorry about not getting back earlier...the issue has been fixed - not sure how or why. I couldn't get the approval to send you a clone of our database. Thanks for your input.

Incorrect Results with t-sql Query in SQL Server 2005

I'm seeing some change in behavior for a query in SQL Server 2005 (compared to behavior in SQL Server 2000). The query is as follows:
create table #projects (projectid int) insert into #projects select projectid from tblprojects where istemplate = 0 and projecttemplateid = 365

Select distinct tblProjects.ProjectID
from tblProjects WITH (NOLOCK)
inner join #projects on #projects.projectid = tblprojects.projectid
Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID = tblMilestones.ProjectID
and tblProjects.projectID in (
select projectid
from tblMilestones
where (parent = 683691 AND PrimaryDate between '4/15/2006' and '4/22/2006' )
and enabled = 1 )
This is dynamic SQL generated by the application when a user requests a report with variable parameters. It works fine in SQL Server 2000. It outputs 47 records which is correct.

In SQL Server 2005, for some reason, the DISTINCT keyword is behaving as a TOP operator and outputs just 1 record. (Results of Showplan Text at the end of this post).

If I modify the query even the slightest bit by:
1) Changing "where (parent = 683691 AND PrimaryDate between '4/15/2006' and '4/22/2006' )
and enabled = 1 )"
To " where (parent = 683691 AND PrimaryDate between '4/15/2006' and '4/22/2006' ) )
and enabled = 1 "

2) Changing " Select distinct tblProjects.ProjectID"
To " Select distinct tblProjects.ProjectID+''"

3) Removing the Distinct keyword, storing into a Temp table, then performing a distinct on the temp table

4) Adding: OPTION (FORCE ORDER)

5) OR completely fixing the query (remove redundant loops, etc)

...it works fine (outputs 47 records). It also works if I created new tables (eg. tMilestones instead of tblMilestones) and inserted about 10 records into each and ran the query referencing these new tables.

I reindexed the tables, updated stats, updated usage, ran DBCC FREEPROCCACHE, changed MaxDOP settings...nothing makes the query behave the way it does in SQL Server 2000 without modifying the query/adding the query hint.

Have you come across this? Any ideas on what might be causing the "TOP" operation. (Somewhat resembles the bug mentioned in this article: http://www.kbalertz.com/Feedback_910392.aspx - but this was apparently fixed POST-SQL Server 2000 SP4 - so has it not made it into SQL Server 2005 yet?).

I will appreciate any new insights you might have on this issue.
Thanks much,
Smitha

P.S. Results of Showplan Text:

StmtText

SET STATISTICS PROFILE ON

(1 row(s) affected)

StmtText

Select distinct tblProjects.ProjectID from tblProjects WITH (NOLOCK)
inner join #projects on #projects.projectid = tblprojects.projectid
Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID = tblMilestones.ProjectID
and tblProjects.projectID in (
select tblMilestones.projectid from tblMilestones
where (parent = 683691 AND tblMilestones.PrimaryDate between '4/15/2006' and '4/22/2006' )
and tblMilestones.enabled = 1 )

(1 row(s) affected)

StmtText

|--Stream Aggregate(DEFINE:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID]=ANY([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID])))
|--Nested Loops(Inner Join, OUTER REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
|--Nested Loops(Inner Join, OUTER REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
| |--Filter(WHERE:(CONVERT_IMPLICIT(tinyint,[ExpesiteProductionCopy].[dbo].[tblMilestones].[Enabled],0)=(1)))
| | |--Nested Loops(Inner Join, OUTER REFERENCES:([Uniq1014], [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) OPTIMIZED)
| | |--Merge Join(Inner Join, MERGE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID], [Uniq1014])=([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID], [Uniq1014]), RESIDUAL:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] = [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] AND [Uniq1014] = [Uniq1014]))
| | | |--Sort(ORDER BY:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] ASC, [Uniq1014] ASC))
| | | | |--Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byPrimaryDate]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate] >= '2006-04-15 00:00:00.000' AND [ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate] <= '2006-04-22 00:00:00.000') ORDERED FORWARD)
| | | |--Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byParentID]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[Parent]=(683691)) ORDERED FORWARD)
| | |--Clustered Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] AND [Uniq1014]=[Uniq1014]) LOOKUP ORDERED FORWARD)
| |--Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblProjects].[PK_tblProjects_1]), SEEK:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID]=[ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)
|--Top(TOP EXPRESSION:((1)))
|--Nested Loops(Inner Join)
|--Table Scan(OBJECT:([tempdb].[dbo].[#projects]), WHERE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[tempdb].[dbo].[#projects].[projectid]))
|--Clustered Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)

(15 row(s) affected)

StmtText
--
SET STATISTICS PROFILE OFF

(1 row(s) affected)

It would be great if you reported this at http://lab.msdn.microsoft.com/productfeedback. If you do, you are more likely to get the attention of the right people, and you might find out if this is a known bug, and if so, what the status is. Steve Kass Drew University Smitha_Expesite@.discussions.microsoft.com wrote:
> I'm seeing some change in behavior for a query in SQL Server 2005
> (compared to behavior in SQL Server 2000). The query is as follows:
>
> create table #projects (projectid int) insert into #projects select
> projectid from tblprojects where istemplate = 0 and projecttemplateid =
> 365
>
> Select distinct tblProjects.ProjectID
> from tblProjects WITH (NOLOCK)
> inner join #projects on #projects.projectid = tblprojects.projectid
> Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID =
> tblMilestones.ProjectID
> and tblProjects.projectID in (
> select projectid
> from tblMilestones b
> where (parent = 683691 AND PrimaryDate between
> '4/15/2006' and '4/22/2006' )
> and enabled = 1 )
>
> This is dynamic SQL generated by the application when a user requests a
> report with variable parameters. It works fine in SQL Server 2000. It
> outputs 47 records which is correct.
>
> In SQL Server 2005, for some reason, the DISTINCT keyword is behaving as
> a TOP operator and outputs just 1 record. (Results of Showplan Text at
> the end of this post).
>
> If I modify the query even the slightest bit by:
> 1) Changing "where (parent = 683691 AND PrimaryDate between '4/15/2006'
> and '4/22/2006' )
> and enabled = 1 )"
> To " where (parent = 683691 AND PrimaryDate between '4/15/2006' and
> '4/22/2006' ) )
> and enabled = 1 "
>
> 2) Changing " Select distinct tblProjects.ProjectID"
> To " Select distinct tblProjects.ProjectID+''"
>
> 3) Removing the Distinct keyword, storing into a Temp table, then
> performing a distinct on the temp table
>
> 4) Adding: OPTION (FORCE ORDER)
>
> 5) OR completely fixing the query (remove redundant loops, etc)
>
> ...it works fine (outputs 47 records). It also works if I created new
> tables (eg. tMilestones instead of tblMilestones) and inserted about 10
> records into each and ran the query referencing these new tables.
>
> I reindexed the tables, updated stats, updated usage, ran DBCC
> FREEPROCCACHE, changed MaxDOP settings...nothing makes the query behave
> the way it does in SQL Server 2000 without modifying the query/adding
> the query hint.
>
> Have you come across this? Any ideas on what might be causing the "TOP"
> operation. (Somewhat resembles the bug mentioned in this article:
> http://www.kbalertz.com/Feedback_910392.aspx - but this was apparently
> fixed POST-SQL Server 2000 SP4 - so has it not made it into SQL Server
> 2005 yet?).
>
> I will appreciate any new insights you might have on this issue.
> Thanks much,
> Smitha
>
>
> P.S. Results of Showplan Text:
>
> StmtText
>
> SET STATISTICS PROFILE ON
>
> (1 row(s) affected)
>
> StmtText
>
>
>
>
>
>
>
> Select distinct tblProjects.ProjectID from tblProjects WITH (NOLOCK)
> inner join #projects on #projects.projectid = tblprojects.projectid
> Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID =
> tblMilestones.ProjectID
> and tblProjects.projectID in (
> select tblMilestones.projectid from tblMilestones
> where (parent = 683691 AND tblMilestones.PrimaryDate between '4/15/2006'
> and '4/22/2006' )
> and tblMilestones.enabled = 1 )
>
> (1 row(s) affected)
>
> StmtText
>
>
>
>
>
>
> |--Stream
> Aggregate(DEFINE:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectI
> D]=ANY([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID])))
> |--Nested Loops(Inner Join, OUTER
> REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
> |--Nested Loops(Inner Join, OUTER
> REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
> |
> |--Filter(WHERE:(CONVERT_IMPLICIT(tinyint,[ExpesiteProductionCopy].[dbo]
> .[tblMilestones].[Enabled],0)=(1)))
> | | |--Nested Loops(Inner Join, OUTER
> REFERENCES:([Uniq1014],
> [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) OPTIMIZED)
> | | |--Merge Join(Inner Join,
> MERGE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID],
> [Uniq1014])=([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID],
> [Uniq1014]),
> RESIDUAL:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] =
> [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] AND
> [Uniq1014] = [Uniq1014]))
> | | | |--Sort(ORDER
> BY:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] ASC,
> [Uniq1014] ASC))
> | | | | |--Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byPrimaryDa
> te]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate]
> >>= '2006-04-15 00:00:00.000' AND
>
> [ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate] <=
> '2006-04-22 00:00:00.000') ORDERED FORWARD)
> | | | |--Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byParentID]
> ),
> SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[Parent]=(683691))
> ORDERED FORWARD)
> | | |--Clustered Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid])
> ,
> SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[Expesi
> teProductionCopy].[dbo].[tblMilestones].[ProjectID] AND
> [Uniq1014]=[Uniq1014]) LOOKUP ORDERED FORWARD)
> | |--Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblProjects].[PK_tblProject
> s_1]),
> SEEK:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID]=[Expesite
> ProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)
> |--Top(TOP EXPRESSION:((1)))
> |--Nested Loops(Inner Join)
> |--Table Scan(OBJECT:([tempdb].[dbo].[#projects]),
> WHERE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[tempd
> b].[dbo].[#projects].[projectid]))
> |--Clustered Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid])
> ,
> SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[Expesi
> teProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)
>
> (15 row(s) affected)
>
> StmtText
> --
> SET STATISTICS PROFILE OFF
>
> (1 row(s) affected)
>
>
>
>
>
>|||OK...I will report it to the Feedback folks. Thanks!|||

The Hotfix that you mentioned (http://www.kbalertz.com/Feedback_910392.aspx) is fixed in SQL Server 2005 RTM, so you may have discovered a new bug in SQL. If so, I would like to fix it. However, I do not have enough information to do that yet.

The first thing I would recommend is to send me a clone of your database. This is a version with no data, but with all the statistics intact (as though the tables were large), so we will get the same plans.

Please contact me for help making the clone.

Marc Friedman

marcfr@.removethispart.microsoft.com

|||Sorry about not getting back earlier...the issue has been fixed - not sure how or why. I couldn't get the approval to send you a clone of our database. Thanks for your input.sql

Incorrect Results with t-sql Query in SQL Server 2005

I'm seeing some change in behavior for a query in SQL Server 2005 (compared to behavior in SQL Server 2000). The query is as follows:
create table #projects (projectid int) insert into #projects select projectid from tblprojects where istemplate = 0 and projecttemplateid = 365

Select distinct tblProjects.ProjectID
from tblProjects WITH (NOLOCK)
inner join #projects on #projects.projectid = tblprojects.projectid
Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID = tblMilestones.ProjectID
and tblProjects.projectID in (
select projectid
from tblMilestones
where (parent = 683691 AND PrimaryDate between '4/15/2006' and '4/22/2006' )
and enabled = 1 )
This is dynamic SQL generated by the application when a user requests a report with variable parameters. It works fine in SQL Server 2000. It outputs 47 records which is correct.

In SQL Server 2005, for some reason, the DISTINCT keyword is behaving as a TOP operator and outputs just 1 record. (Results of Showplan Text at the end of this post).

If I modify the query even the slightest bit by:
1) Changing "where (parent = 683691 AND PrimaryDate between '4/15/2006' and '4/22/2006' )
and enabled = 1 )"
To " where (parent = 683691 AND PrimaryDate between '4/15/2006' and '4/22/2006' ) )
and enabled = 1 "

2) Changing " Select distinct tblProjects.ProjectID"
To " Select distinct tblProjects.ProjectID+''"

3) Removing the Distinct keyword, storing into a Temp table, then performing a distinct on the temp table

4) Adding: OPTION (FORCE ORDER)

5) OR completely fixing the query (remove redundant loops, etc)

...it works fine (outputs 47 records). It also works if I created new tables (eg. tMilestones instead of tblMilestones) and inserted about 10 records into each and ran the query referencing these new tables.

I reindexed the tables, updated stats, updated usage, ran DBCC FREEPROCCACHE, changed MaxDOP settings...nothing makes the query behave the way it does in SQL Server 2000 without modifying the query/adding the query hint.

Have you come across this? Any ideas on what might be causing the "TOP" operation. (Somewhat resembles the bug mentioned in this article: http://www.kbalertz.com/Feedback_910392.aspx - but this was apparently fixed POST-SQL Server 2000 SP4 - so has it not made it into SQL Server 2005 yet?).

I will appreciate any new insights you might have on this issue.
Thanks much,
Smitha

P.S. Results of Showplan Text:

StmtText

SET STATISTICS PROFILE ON

(1 row(s) affected)

StmtText

Select distinct tblProjects.ProjectID from tblProjects WITH (NOLOCK)
inner join #projects on #projects.projectid = tblprojects.projectid
Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID = tblMilestones.ProjectID
and tblProjects.projectID in (
select tblMilestones.projectid from tblMilestones
where (parent = 683691 AND tblMilestones.PrimaryDate between '4/15/2006' and '4/22/2006' )
and tblMilestones.enabled = 1 )

(1 row(s) affected)

StmtText

|--Stream Aggregate(DEFINE:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID]=ANY([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID])))
|--Nested Loops(Inner Join, OUTER REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
|--Nested Loops(Inner Join, OUTER REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
| |--Filter(WHERE:(CONVERT_IMPLICIT(tinyint,[ExpesiteProductionCopy].[dbo].[tblMilestones].[Enabled],0)=(1)))
| | |--Nested Loops(Inner Join, OUTER REFERENCES:([Uniq1014], [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) OPTIMIZED)
| | |--Merge Join(Inner Join, MERGE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID], [Uniq1014])=([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID], [Uniq1014]), RESIDUAL:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] = [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] AND [Uniq1014] = [Uniq1014]))
| | | |--Sort(ORDER BY:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] ASC, [Uniq1014] ASC))
| | | | |--Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byPrimaryDate]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate] >= '2006-04-15 00:00:00.000' AND [ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate] <= '2006-04-22 00:00:00.000') ORDERED FORWARD)
| | | |--Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byParentID]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[Parent]=(683691)) ORDERED FORWARD)
| | |--Clustered Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] AND [Uniq1014]=[Uniq1014]) LOOKUP ORDERED FORWARD)
| |--Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblProjects].[PK_tblProjects_1]), SEEK:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID]=[ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)
|--Top(TOP EXPRESSION:((1)))
|--Nested Loops(Inner Join)
|--Table Scan(OBJECT:([tempdb].[dbo].[#projects]), WHERE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[tempdb].[dbo].[#projects].[projectid]))
|--Clustered Index Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)

(15 row(s) affected)

StmtText
--
SET STATISTICS PROFILE OFF

(1 row(s) affected)

It would be great if you reported this at http://lab.msdn.microsoft.com/productfeedback. If you do, you are more likely to get the attention of the right people, and you might find out if this is a known bug, and if so, what the status is. Steve Kass Drew University Smitha_Expesite@.discussions.microsoft.com wrote:
> I'm seeing some change in behavior for a query in SQL Server 2005
> (compared to behavior in SQL Server 2000). The query is as follows:
>
> create table #projects (projectid int) insert into #projects select
> projectid from tblprojects where istemplate = 0 and projecttemplateid =
> 365
>
> Select distinct tblProjects.ProjectID
> from tblProjects WITH (NOLOCK)
> inner join #projects on #projects.projectid = tblprojects.projectid
> Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID =
> tblMilestones.ProjectID
> and tblProjects.projectID in (
> select projectid
> from tblMilestones b
> where (parent = 683691 AND PrimaryDate between
> '4/15/2006' and '4/22/2006' )
> and enabled = 1 )
>
> This is dynamic SQL generated by the application when a user requests a
> report with variable parameters. It works fine in SQL Server 2000. It
> outputs 47 records which is correct.
>
> In SQL Server 2005, for some reason, the DISTINCT keyword is behaving as
> a TOP operator and outputs just 1 record. (Results of Showplan Text at
> the end of this post).
>
> If I modify the query even the slightest bit by:
> 1) Changing "where (parent = 683691 AND PrimaryDate between '4/15/2006'
> and '4/22/2006' )
> and enabled = 1 )"
> To " where (parent = 683691 AND PrimaryDate between '4/15/2006' and
> '4/22/2006' ) )
> and enabled = 1 "
>
> 2) Changing " Select distinct tblProjects.ProjectID"
> To " Select distinct tblProjects.ProjectID+''"
>
> 3) Removing the Distinct keyword, storing into a Temp table, then
> performing a distinct on the temp table
>
> 4) Adding: OPTION (FORCE ORDER)
>
> 5) OR completely fixing the query (remove redundant loops, etc)
>
> ...it works fine (outputs 47 records). It also works if I created new
> tables (eg. tMilestones instead of tblMilestones) and inserted about 10
> records into each and ran the query referencing these new tables.
>
> I reindexed the tables, updated stats, updated usage, ran DBCC
> FREEPROCCACHE, changed MaxDOP settings...nothing makes the query behave
> the way it does in SQL Server 2000 without modifying the query/adding
> the query hint.
>
> Have you come across this? Any ideas on what might be causing the "TOP"
> operation. (Somewhat resembles the bug mentioned in this article:
> http://www.kbalertz.com/Feedback_910392.aspx - but this was apparently
> fixed POST-SQL Server 2000 SP4 - so has it not made it into SQL Server
> 2005 yet?).
>
> I will appreciate any new insights you might have on this issue.
> Thanks much,
> Smitha
>
>
> P.S. Results of Showplan Text:
>
> StmtText
>
> SET STATISTICS PROFILE ON
>
> (1 row(s) affected)
>
> StmtText
>
>
>
>
>
>
>
> Select distinct tblProjects.ProjectID from tblProjects WITH (NOLOCK)
> inner join #projects on #projects.projectid = tblprojects.projectid
> Inner join tblMilestones WITH (NOLOCK) ON tblProjects.ProjectID =
> tblMilestones.ProjectID
> and tblProjects.projectID in (
> select tblMilestones.projectid from tblMilestones
> where (parent = 683691 AND tblMilestones.PrimaryDate between '4/15/2006'
> and '4/22/2006' )
> and tblMilestones.enabled = 1 )
>
> (1 row(s) affected)
>
> StmtText
>
>
>
>
>
>
> |--Stream
> Aggregate(DEFINE:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectI
> D]=ANY([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID])))
> |--Nested Loops(Inner Join, OUTER
> REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
> |--Nested Loops(Inner Join, OUTER
> REFERENCES:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]))
> |
> |--Filter(WHERE:(CONVERT_IMPLICIT(tinyint,[ExpesiteProductionCopy].[dbo]
> .[tblMilestones].[Enabled],0)=(1)))
> | | |--Nested Loops(Inner Join, OUTER
> REFERENCES:([Uniq1014],
> [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]) OPTIMIZED)
> | | |--Merge Join(Inner Join,
> MERGE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID],
> [Uniq1014])=([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID],
> [Uniq1014]),
> RESIDUAL:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] =
> [ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] AND
> [Uniq1014] = [Uniq1014]))
> | | | |--Sort(ORDER
> BY:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID] ASC,
> [Uniq1014] ASC))
> | | | | |--Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byPrimaryDa
> te]), SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate]
> >>= '2006-04-15 00:00:00.000' AND
>
> [ExpesiteProductionCopy].[dbo].[tblMilestones].[PrimaryDate] <=
> '2006-04-22 00:00:00.000') ORDERED FORWARD)
> | | | |--Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[byParentID]
> ),
> SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[Parent]=(683691))
> ORDERED FORWARD)
> | | |--Clustered Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid])
> ,
> SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[Expesi
> teProductionCopy].[dbo].[tblMilestones].[ProjectID] AND
> [Uniq1014]=[Uniq1014]) LOOKUP ORDERED FORWARD)
> | |--Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblProjects].[PK_tblProject
> s_1]),
> SEEK:([ExpesiteProductionCopy].[dbo].[tblProjects].[ProjectID]=[Expesite
> ProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)
> |--Top(TOP EXPRESSION:((1)))
> |--Nested Loops(Inner Join)
> |--Table Scan(OBJECT:([tempdb].[dbo].[#projects]),
> WHERE:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[tempd
> b].[dbo].[#projects].[projectid]))
> |--Clustered Index
> Seek(OBJECT:([ExpesiteProductionCopy].[dbo].[tblMilestones].[projectid])
> ,
> SEEK:([ExpesiteProductionCopy].[dbo].[tblMilestones].[ProjectID]=[Expesi
> teProductionCopy].[dbo].[tblMilestones].[ProjectID]) ORDERED FORWARD)
>
> (15 row(s) affected)
>
> StmtText
> --
> SET STATISTICS PROFILE OFF
>
> (1 row(s) affected)
>
>
>
>
>
>|||OK...I will report it to the Feedback folks. Thanks!|||

The Hotfix that you mentioned (http://www.kbalertz.com/Feedback_910392.aspx) is fixed in SQL Server 2005 RTM, so you may have discovered a new bug in SQL. If so, I would like to fix it. However, I do not have enough information to do that yet.

The first thing I would recommend is to send me a clone of your database. This is a version with no data, but with all the statistics intact (as though the tables were large), so we will get the same plans.

Please contact me for help making the clone.

Marc Friedman

marcfr@.removethispart.microsoft.com

|||Sorry about not getting back earlier...the issue has been fixed - not sure how or why. I couldn't get the approval to send you a clone of our database. Thanks for your input.

Incorrect results if no TOP clause

I have a problem with a query. When I omit the TOP clause I get more
rows returned than I expect (12 rows out of a 119 in the table), but
when I include TOP I get 5 rows from the same data with the otherwise
unchanged table.
Thing is, the query where I include TOP 1000 is the correct result.
I'm on SQL Server 2000, select @.@.version -
"Microsoft SQL Server 2000 - 8.00.194 (Intel X86) Aug 6 2000
00:57:48 Copyright (c) 1988-2000 Microsoft Corporation Developer
Edition on Windows NT 5.1 (Build 2600: Service Pack 1) "
I've cut the query down quite a bit, the table
create table Test (
CDMA_PDSN63 FLOAT,
AVE__CORE_46_CountINTEGER,
AVE__CORE_46_Sum FLOAT);
The query is
SELECT * FROM (
SELECT
-- TOP 1000 -- comment this in to get correct results
D.CDMA_PDSN63, NM.AVE__CORE_46x AVE__CORE_46
FROM (SELECT DISTINCT CDMA_PDSN63
FROM(SELECT CDMA_PDSN63 FROM Test ) AS dims
) AS D,
(SELECT CDMA_PDSN63,
CASE when (Sum( AVE__CORE_46_Count))=0 then NULL else
SUM(AVE__CORE_46_Sum) / SUM( AVE__CORE_46_Count) end AS AVE__CORE_46x
FROM Test GROUP BY CDMA_PDSN63) AS NM
WHERE D.CDMA_PDSN63*=NM.CDMA_PDSN63
) as MainQuery
WHERE ROUND(MainQuery.AVE__CORE_46,0) >= 120
--AND MainQuery.AVE__CORE_46 IS NOT NULL - Note 1
--ORDER BY CDMA_PDSN63 - Note 2
Note 1: I tried adding this but it makes not difference
Note 2: this was in the original query, it makes sense to have it but
again it makes no difference, I've used in on the inner and outer
select, no change
I've also tried TOP 1000 in the outer select again no difference.
Changing the outer join to a regular join fixes the problem, but I
need the outer join in the original query. (In the original query
there are many more sub-selects and several more outer join clauses to
put them back together.)
If I use small values for TOP n (e.g. 1, 2, ... < 10) the results are
even stranger, I get a subset of the expected rows, and not the same
number as n.
I tried setting a rowcount as well, no difference.
I've seen several other queries on this newsgroup which talk about
similar problems but the threads have never been concluded with a
clear answer.
Any ideas? Thanks
allan
> "Microsoft SQL Server 2000 - 8.00.194
You're on RTM! Install Service Pack 3a, right away, please! There are many
query processor bugs that have been fixed since the product was released.
Thanks for the CREATE TABLE, but once you've done that, you're going to have
to provide us with enough sample data to reproduce your problem (as well as
tell us which rows you were expecting in the result set!). Otherwise, it's
impossible for us to determine exactly what's happening, why it doesn't meet
your criteria, and test our suggestions on fixing it...
See http://www.aspfaq.com/5006
http://www.aspfaq.com/
(Reverse address to reply.)
|||Allan,
After you install service pack 3a as Aaron suggested, I suggest you
consider two other things:
* Rwrite the query using ANSI outer join syntax (... left outer join on
...), which, unlike *=, is always unambiguous
* Consider a different data type than FLOAT for data that must be
compared with the = operator. Because FLOAT values are approximate, you
cannot count on tests of equality to be reliable.
Steve Kass
Drew University
Allan Kelly wrote:

>I have a problem with a query. When I omit the TOP clause I get more
>rows returned than I expect (12 rows out of a 119 in the table), but
>when I include TOP I get 5 rows from the same data with the otherwise
>unchanged table.
>Thing is, the query where I include TOP 1000 is the correct result.
>I'm on SQL Server 2000, select @.@.version -
>"Microsoft SQL Server 2000 - 8.00.194 (Intel X86) Aug 6 2000
>00:57:48 Copyright (c) 1988-2000 Microsoft Corporation Developer
>Edition on Windows NT 5.1 (Build 2600: Service Pack 1) "
>I've cut the query down quite a bit, the table
>create table Test (
>CDMA_PDSN63 FLOAT,
>AVE__CORE_46_CountINTEGER,
>AVE__CORE_46_Sum FLOAT);
>The query is
>SELECT * FROM (
>SELECT
>-- TOP 1000 -- comment this in to get correct results
>D.CDMA_PDSN63, NM.AVE__CORE_46x AVE__CORE_46
>FROM (SELECT DISTINCT CDMA_PDSN63
>FROM(SELECT CDMA_PDSN63 FROM Test ) AS dims
>) AS D,
>(SELECT CDMA_PDSN63,
>CASE when (Sum( AVE__CORE_46_Count))=0 then NULL else
>SUM(AVE__CORE_46_Sum) / SUM( AVE__CORE_46_Count) end AS AVE__CORE_46x
>FROM Test GROUP BY CDMA_PDSN63) AS NM
>WHERE D.CDMA_PDSN63*=NM.CDMA_PDSN63
>) as MainQuery
>WHERE ROUND(MainQuery.AVE__CORE_46,0) >= 120
>--AND MainQuery.AVE__CORE_46 IS NOT NULL - Note 1
>--ORDER BY CDMA_PDSN63 - Note 2
>Note 1: I tried adding this but it makes not difference
>Note 2: this was in the original query, it makes sense to have it but
>again it makes no difference, I've used in on the inner and outer
>select, no change
>I've also tried TOP 1000 in the outer select again no difference.
>Changing the outer join to a regular join fixes the problem, but I
>need the outer join in the original query. (In the original query
>there are many more sub-selects and several more outer join clauses to
>put them back together.)
>If I use small values for TOP n (e.g. 1, 2, ... < 10) the results are
>even stranger, I get a subset of the expected rows, and not the same
>number as n.
>I tried setting a rowcount as well, no difference.
>I've seen several other queries on this newsgroup which talk about
>similar problems but the threads have never been concluded with a
>clear answer.
>Any ideas? Thanks
>allan
>
|||Steve Kass <skass@.drew.edu> wrote in message news:<#Tj3pA0dEHA.1604@.TK2MSFTNGP11.phx.gbl>...
> Allan,
> After you install service pack 3a as Aaron suggested, I suggest you
> consider two other things:
> * Rwrite the query using ANSI outer join syntax (... left outer join on
> ...), which, unlike *=, is always unambiguous
> * Consider a different data type than FLOAT for data that must be
> compared with the = operator. Because FLOAT values are approximate, you
> cannot count on tests of equality to be reliable.
>
Thanks Aaron, Steve,
I rewrote the SQL using ANSI outer join syntax and that fixes the
problem. Great!
Thanks for the reminder to look into the service pack, my code need to
run against MSDE in the final product so I need to check out the
service pack situation there.
allan