SUM Returns Incorrect Value In SQL Server Mobile Query ... Bug??
Feb 6, 2007
Hi all,
I am a newcomer to Microsoft Database Technology and have appeared to come across an issue with the SUM function in SQL Server Mobile Edition.
I am running Visual Studio 2005 and have created 2 tables:
Orders and OrderLines which are set up in master detail fashion.
The SQL Statement I create in the Query Builder is as follows:
SELECT Orders.OrderNo, Orders.OrderDate, Orders.Priority, Orders.Address, SUM(OrderLines.Quantity * OrderLines.QualityReference) AS Total
FROM Orders, OrderLines
WHERE Orders.OrderNo = OrderLines.OrderNo
GROUP BY Orders.OrderNo, Orders.OrderDate, Orders.Priority, Orders.Address
Now, the SUM returns a total for all records in the OrderLines table, and not just the records whose OrderNo is the same as Orders.OrderNo
Can someone out there please clarify whether its an issue with my code or a bug with SQL Server Mobile???
Here are a couple of screenshots which will demonstrate what I mean.
Here is the contents of the Orders and OrderLines tables. Each order has only 1 line item in it.
When performing the summation over the OrderLines table, it produces the SUM of the all records in OrderLines and not according to the GROUP BY clause. See the following screen shot.
I'm working with PivotTable on Excel 2000 which is connected to an OLAP server (from SQL Server 7 installation). The pivot is intended to analyze Sales during April 2001. Yesterday I found out that OLAP/Excel returned/displayed inconsistent data. The 'April Total' value is NOT equal to the 'Quarter 2 Total' (I already inspected the underlying database and sure that there is absolutely NO data for months after April 2001). The value for 'April Total' is the correct one. I'm not sure whether the problem resides on the OLAP Server or Excel (pivot) itself. For ones who like to help me I would be glad to supply you with the screenshots (just email me). Please help.
When I use the following to get the StoredProc parameters, the IN variables are returned correctly as "IN" but all the OUT variables returned as "INOUT" in the PARAMETER_MODE instead of "OUT". Is this a bug?
SELECT PARAMETER_MODE,PARAMETER_NAME,DATA_TYPE FROM INFORMATION_SCHEMA.PARAMETERS WHERE SPECIFIC_NAME = 'SPName_with_IN_OUT_Variables'"
STDEV() gives incorrect values with reasonable input.
I have a table filled with GPS readings. I've got a column LATITUDE (FLOAT) with about 20,000 records between 35.6369018 and 35.639890. (Same value to the first 5 digits of precision---what can i say, it's a good gps.)
Here's what happens when I ask SQL Server ("9.00.1399.06 (IntelX86)") to compute the standard deviation of the latitude:
// Transact-SQL StdDev function:
SELECT STDEV(LATITUDE) FROM GPSHISTORY WHERE STATTIME BETWEEN '2007-10-23 11:21:00.859' AND '2007-10-23 17:00:00.062' AND GPSDEVICEID = 0x004A08BC04050000;
0
// Zero. ZERO??!?!! //Let's re-implement Std Dev from the definition using other aggregate functions:
DECLARE @AVERAGE FLOAT; SELECT @AVERAGE = AVG(LATITUDE) FROM GPSHISTORY WHERE GPSDATE BETWEEN '2007-10-23 11:21:00.859' AND '2007-10-23 17:00:00.062' AND GPSDEVICEID = 0x004A08BC04050000; SELECT SQRT(SUM(SQUARE((LATITUDE - @AVERAGE)))/COUNT(LATITUDE)) FROM GPSHISTORY WHERE GPSDATE BETWEEN '2007-10-23 11:21:00.859' AND '2007-10-23 17:00:00.062' AND GPSDEVICEID = 0x004A08BC04050000;
6.03401924005392E-06
// That's better. Maybe STDEV is using fixed point arithmetic?!?
SELECT STDEV(10 * LATITUDE)/10 FROM GPSHISTORY WHERE GPSDATE BETWEEN '2007-10-23 11:21:00.859' AND '2007-10-23 17:00:00.062' AND GPSDEVICEID = 0x004A08BC04050000;
4.77267753808509E-06
SELECT STDEV(100 * LATITUDE)/100 FROM GPSHISTORY WHERE GPSDATE BETWEEN '2007-10-23 11:21:00.859' AND '2007-10-23 17:00:00.062' AND GPSDEVICEID = 0x004A08BC04050000;
1.66904329068838E-05
SELECT STDEV(1000 * LATITUDE)/1000 FROM GPSHISTORY WHERE GPSDATE BETWEEN '2007-10-23 11:21:00.859' AND '2007-10-23 17:00:00.062' AND GPSDEVICEID = 0x004A08BC04050000;
8.11904280806654E-06
// The standard deviation should, of course, be linear, e.g.
DECLARE @AVERAGE FLOAT; SELECT @AVERAGE = AVG(LATITUDE) FROM GPSHISTORY WHERE GPSDATE BETWEEN '2007-10-23 11:21:00.859' AND '2007-10-23 17:00:00.062' AND GPSDEVICEID = 0x004A08BC04050000; SELECT SQRT(SUM(SQUARE(100*(LATITUDE - @AVERAGE)))/COUNT(LATITUDE))/100 FROM GPSHISTORY WHERE GPSDATE BETWEEN '2007-10-23 11:21:00.859' AND '2007-10-23 17:00:00.062' AND GPSDEVICEID = 0x004A08BC04050000;
6.03401924005389E-06
// Std Dev is a numerically stable computation, although it does require traversing the dataset twice. // // This calculation is not being done correctly. // // Incidently, SQRT(VAR(Latitude....)) gives 4.80354E-4, which is also way off.
I will redefine STDEV to use a stored procedure similar to the above, but the algorithm used to compute VAR, STDEV etc should be reviewed and fixed.
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 "
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 )
I only want to UniqIds that only have the CODE of ABC... and if it contains ANYTHING other than ABC then It doesnt return that UniqID... Now keep in mind there's multiple different codes.. I'm just looking for a bit of code that drops any ID's that don't have my criteria.
I don't understand why I am having this error. It does create the database on AddSubscription() method but it is failing opening the database on Synchronise(). I have also tried uninstalling and then reinstalling all the SQL Mobile components in the following order.
I have a program in VB.NET 2003 where I have query "SELECT COUNT(*) FROM master..sysservers WHERE srvname = '" & strServerName & "'". This program copies data from .MDF file to another .MDF file. This query is written since I have created linked server.
Issue 1: But now I to copy data from .SDF (SQL Server Mobile Edition) to desktop .MDF file. For this I cannot fire the above query on .SDF file. What is the other alternative?
Issue 2: In the existing prgram that copies data from .MDF to .MDF, I have created linked server. Can I do the same with mobile edition?
I am developping a non-managed C++ application for PocketPC using a SQL Server mobile database.
The application is compiled for PocketPC 2003 and uses SQL Server Mobile v2. I use Visual Studio 2005. But I need to compile the application for Windows Mobile 5.0 devices. So I installed the WM5 SDK and had the WM5 into my project configuration.
The "ssceoledb.h" which I include incluses the "transact.h" file. But my problem is that this file is only provided with the PocketPC 2003 SDK and not in the WM5 SDK. So I cannot use the WM5 configuration project with SQL Server. I also tried with the last SQL Server Mobile 2005 (ie v3.0) and the "ssceoledb30.h" also includes "transact.h".
Did I miss something to install ? Do you know how I can resolve the problem ?
Using MS VS 2005 (incl SQL Server Mobile) MS Pocket PC 2005 SDK
I am working on a project that builds for Pocket PC on both Mobile 2003 and Mobile 5. The project uses/will use SQL Server Mobile to store local data.
Project created from new with support for both platforms. I include required header files ssceerr30.h and ssceoledb30.h.
Project builds fine in WM2003 configuration, release and debug.
When I build for WM5 the compiler cannot find the header file transact.h. This is included from within ssceoledb30.h. Same as under WM2003.
In WM2003 configuration if I highlight the ssceoledb30.h include in Visual Studio and open the header, it takes me to <Visual Studio dir>SmartDevicesSDKSQL ServerMobilev3.0. I then locate the include for transact.h and do the same, which takes me <Visual Studio dir>SDKPocketPC2003include. The file exists.
If I repeat the above 'browsing' under the WM5 configuration, ssceoledb30.h takes me to a different copy in the WM5 SDK directory. There is no diff between the file here and the other copy used by WM2003. If I attempt to open transact.h - file does not exist.
Fix (which I'm not too sure about, i.e. is it OK?) - If I copy transact.h to the WM5 SDK directory, the project builds.
Why has transact.h disappeared from WM5 SDK? I can find no ref's to this problem anywhere. Is my installation of the WM5 SDK corrupt? What else could I be missing? Is there a sample for SQL Server mobile (like the NorthwindOLEDB sample) that comes configured to build for WM5?
Hi folks, I'm new to Windows Mobile progamming, and new to this forum. Apologies in advance if I'm asking a boneheaded question, but I've done searches and can't find anything directly applicable to my problem.
I'm currently walking through the published MS tutorial in setting up an SQL Server 2005 Mobile application that subscribes to a publication on SQL Server 2005 to exchange information.
I've gotten almost all the way through... successfully set up the server components, creating the publication, etc. On the mobile side, I've been able run the cab files to install the SQL Mobile components and to create the project, add the reference to the dll, and instantiate an engine object. It compiles.
The step in the tutorial after that, though, where you specify the data source from the "data" menu, I've got a problem. When I try to use the "new connection" dialog from choosing the data connection, "MS SQL Server Mobile Edition" doesn't show up as a choice. I've tried choosing any of the other combinations, and in teh subsequent "Connection properties" section my database, SQLMobile (as in their sample) is available, but I get an error when I choose it and click OK. Clicking on "Test Connection" gives me a connection successful message.
My guess is that something about the Mobile server side components is not installed correctly on my development machine, but honestly I have no idea how to begin to fix it. Has anyone seen this problem before and know how to resolve it?
Your time and any knowledge sharing is greatly appreciated. Thank you, -Dana
When I try and connecto to SQL CE I always get an invalid operation exception. I"m afraid that I did not follow the proper install for Orcas Beta 2. I can't remember if I was supposed to uninstall SQL Mobile 2005 first or not.
All I know is when I try and use my SQL CE I can't connecto to a DB / sdf file ?
Any help would be appreciated I"m just starting to use SQL CE.
This is a great tutorial and it's a shame one of the more important steps was missed. In the €œCreate the snapshot user€? section you you find the steps to create the snapshot_agent account. Then in the €œCreate the snapshot folder€? section you find the share and folder permissions. However, at no point do the instructions advise you about adding the snapshot_agent to the SQL Server Logins. The result is that agent cannot perform the initial snapshot but you won't find this out until 50 steps later after Step 10 in the section €œCreate a new subscription".
To get back on track, openthe Object Explorer's Security section and add the snapshot_agent to your logins. Then using the "User Mappings", set an appropriate level for the SQLMobile database role. Once completed you then need to run the agent.
Right-click the SQLMobile publication you created and select "View Snapshot Agent status". From that dialog you can select "Start" to run the agent. When it completes, you can return to the tutorial section "Create a new subscription" and continue with the tutorial.
I am studying the tutorial in SQL Server 2005 Mobile Edition Books Online, and the topic is Creating a Mobile Application with SQL Server Mobile. I have got a problem when creating a new subscription after created a new SQL Server Mobile database. And the problem is shown below:
New Subscription Wizard
- Beginning Synchronization (Success)
- Synchronizing Data (100%) (Error) Messages * Failure to connect to SQL Server with provided connection information. SQL Server does not exist, access is denied because the IIS user is not a valid user on the SQL Server, or the password is incorrect. HRESULT 0x80004005 (29061)
* 無法完æˆ?作æ¥ã€‚
- Finalizing Synchronization (Stopped)
- Saving Subscription Properties (Stopped)
Before I have met this problem, I have finished all the task. And I can browse the localhost web site by using anonymous account even I use internet explorer or browse the directly in IIS.
When I was using a simple query using select statement with where clauses, I can get the results. When I use AND to specify more conditions. It returns no row even though I get the result when query seperately. What should be the possible cause of this. I am using SQL Server 6.5. Thank you
select INVOICE.TarrifHeadNumber, SUM(INVOICEITEMS.ItemQuantity) From invoiceitems, invoice Where invoice.invoicenumber = invoiceitems.invoicenumber and month(InvoiceDate)='11' and year(InvoiceDate)= '2012' group by INVOICE.TarrifHeadNumber
Now if i use below query and add invoicetypecode field
select INVOICE.TarrifHeadNumber,CETSH.GoodsDescription, SUM(INVOICEITEMS.ItemQuantity),INVOICE.invoicetype code From invoiceitems, invoice , cetsh Where invoice.invoicenumber = invoiceitems.invoicenumber and month(InvoiceDate)='11' and year(InvoiceDate)= '2012' and cast(CETSH.CETSHNumber as varchar) = INVOICE.TarrifHeadNumber group by INVOICE.TarrifHeadNumber,CETSH.GoodsDescription,in voicetypecode
I have a SP that manipulates data for picking products and puts them into a temp table "#PickList" which is used for the basis of printing a picking note report.
I have also added code at the end of the SP to take the "#PickList" data and insert into a permanent table called "BWT_Lift_Transaction" and then use the bcp command to query it out to a text file. All this works fine, until the bcp command runs. Although the records are in the table, bcp returns nothing. Here is the code:
The earlier parts of the code create the filename for the text file and location to store it. If I insert a SELECT on the dbo.BWT_Lift_Transaction directly after the insert, I can see the data in there, but although the bcp command creates the file correctly, it returns no data:
output
NULL Starting copy... NULL 0 rows copied. Network packet size (bytes): 4096 Clock Time (ms.) Total : 1 NULL
If I remove the delete statement at the end and run the code twice, it will insert the data into the table twice. On the first run, nothing is returned by bcp. On the second run, the first set is returned by bcp, not both sets.
I don't understand why this is, but I guess it's something to do with transaction commitment and the way bcp works.
I'm trying to update column based upon the results of a subquery. I'm getting the error that my Subquery returns more than one result. I've tried adding the EXISTS or IN keywords and cannot get the syntax right. I can't find any examples of how to write this with an Update query.
Here's my query:
UPDATE temp_UpdateRemainingHours SET UsedHours =
(SELECT dbo.vw_SumEnteredHours_byCHARGE_CD.SumEnteredHours, dbo.vw_SumEnteredHours_byCHARGE_CD.CHARGE_CD FROM dbo.vw_SumEnteredHours_byCHARGE_CD INNER JOIN dbo.temp_UpdateRemainingHours ON dbo.vw_SumEnteredHours_byCHARGE_CD.CHARGE_CD = dbo.temp_UpdateRemainingHours.CHARGE_CD)
FROM dbo.vw_SumEnteredHours_byCHARGE_CD, temp_UpdateRemainingHours
WHERE dbo.vw_SumEnteredHours_byCHARGE_CD.CHARGE_CD = dbo.temp_UpdateRemainingHours.CHARGE_CD
I am facing a problem that following query give me different result whenever I execute the query, it returns me same number of records but not all the rows are same everytime it is executed.
Select[Field1] From ( SelectRow_number() Over(Partition By [Field2], [Field3] Order By [Field2], [Field3], [Field4] Desc) ID, * From[dbo].[Table1] ) A WhereID > 1 OrderBy [Field1]
Those highlighted in yellow colours are duplicate records, I need to remove one of them.
This is my syntax, and if I print the value that is stored in each variable @goodtries = 120 @badtries = 25 but when I run the syntax below it gives me 0.00
Declare @goodtries as int, @badtries as int select @goodtries = convert(decimal(18,4),count(userID)) from table1 WHERE logintype IN ('Valid', 'Success') select @badtries = convert(decimal(18,4),count(userID))
I am getting a SQLExcepetion error near , in this query string...so obvicously my query string is wrong... could someone help me get this query string right please...
Thanks "Select OrgID, OrgName From aspnet_OrgNames Where UserID = @UserID, OrgID = @OrgID"
Set @complete = (SELECT Count(pass) as num FROM tblAttempts WHERE userID = @userID AND pass = 1)
If (@complete = 24) Begin Set @status = 'OK' End Else Begin Set @status = 'NOT OK' End GO
CREATE PROCEDURE [dbo].[checkComplete] @userID int,@status varchar (6) output AS DECLARE @complete int SET @complete = (SELECT COUNT(pass) AS num FROM tblAttempts WHERE userID = @userID AND pass = 1) IF (@complete = 24) BEGIN SET @status = 'OK' ENDELSE BEGIN SET @status = 'NOT OK' ENDGO
For reference, I have tried changing intUserID to be a different value (e.g. 13) to ensure it is not that '4' in question - likewise for @complete = 24 (e.g. 23).
Any ideas where the 4 is coming from and what is wrong here?
RevNumber, CureTime, Bump1, Bump1Interval, Bump2, Bump2Interval, DwellTime, LateToDrop, EarlyToDrop, OverTime, CycleTime, ChangeTime, Date FROM HeatInfo WHERE (ShiftNumber = @ShiftNumber)
AND (Date >= @StartDate) AND (Date <= @EndDate)
This correctly returns 4 rows, which is great except that I would like to have these records Sorted by the Date. So I added the OrderBy command to the bottom of the query, like this
RevNumber, CureTime, Bump1, Bump1Interval, Bump2, Bump2Interval, DwellTime, LateToDrop, EarlyToDrop, OverTime, CycleTime, ChangeTime, Date FROM HeatInfo WHERE (ShiftNumber = @ShiftNumber)
AND (Date >= @StartDate) AND (Date <= @EndDate) ORDER BY Date
This query returns 181 rows! whis is not great. What am I doing wrong here, I suppose that it is something extreamly obvious or I would probably have figured it out.
I was doing a demo last night, something that I've done hundreds of times already. Last night was the first time that it has failed to work. I was trying to show what the sys.dm_db_missing_index_* DMVs can provide.
AdventureWorks database
I'm running the following query:
select city from person.address where city like 'A%'
This is supposed to produce a table scan which in turn will obviously cause SQL Server to detect that an index could be beneficial. However, it does a clustered index scan (yes, I know, basically the same thing) instead and I see absolutely nothing appear in the DMVs. I pulled the data out into a dummy table that did not have a primary key either using the following: select * into person.tmpaddress from person.address
I then execute the same query and get a table scan which is expected:
select city from person.address where city like 'A%'
However, it does not matter how much I execute that query or any other permutation of explicit query, absolutely nothing at all gets logged into the sys.dm_db_missing_index_* DMVs. I have also tried this same type of thing with several other tables in the AW database and can not find a single query which will cause anything to be logged to these DMVs. It seems that something is broken, but for the life of me, I can't figure out what is wrong. No weird settings, I'm running as sa, etc.
I can run queries like this in other databases and stuff gets immediately logged to the DMVs as expected. Any ideas?
Hi,I have an Address table which contains more than one addresses for aparticular member. I want to write a query that would only displaymost current address. All addresses have a unique ID (addID).Example:memberID addID address1-------- ------ --------------------------------------------------295 69 13 Auster St295 70 465 Lorre Ct295 71 P.O. Box 321722 171 10 Hannaford Rd722 172 Dubai, United Arab Emirates
I am hoping someone could help me understand why this is happening and perhaps a solution. I am using ASP.NET 2.0 with a SQL 2005 database. In code behind, I am performing a query using a parameter as below: sql = "SELECT field_name FROM myTable WHERE (field_name = @P1)" objCommand.Parameters.Add(New SqlParameter("@P1", TextBox1.Text)) The parameter is obtained from TextBox1 which has valid input. However, the value is not in the table. The query should not return ANY results. However, I am getting one single row back with null values for each field requested in the query. The SQL user account for this query has select, insert, and update permissions on the table. The query is simple, no joins, and the table has no null values in any fields. If I perform the exact same query using an account with select only permission on the table, I get what I was expecting, no records. Then if I go back to the previous user account with more permissioins, and I change the query to pass the paramter this way: sql = String.Format("SELECT field_name FROM myTable WHERE (field_name = {0})", TextBox1.Text) I also get NO records retuned using the same criteria. What is going on here? I would prefer to use the parameterized query method with the account having elevated permissions. Is there some command object setting that can prevent the null row from returning? Thanks!
Hi.I have a table (websitehits) which holds statistics about websites.This table has a date field (datecounted). What I need is to create aquery which returns a list of dates between two date ranges (say ayear ago from today and a year from now) which only shows dates thathaven't been used in the websitehits table for a given website.For example if my table contains something like:Website Datecounted HitsSite101/01/046000Site101/02/046500Site101/03/046250Site201/03/041000Site201/04/041200Site201/05/041500So if query for ‘site1' then I'd get a list of all dates between30/11/03 to 30/11/05 with the exception of the dates 01/01/04,01/02/04 and 01/03/04.So far I've tried to do this using another table named calendar whichcontains a very long list of dates and to use this to produce the list– but I'm not getting very far.By the way I'm using sql server, an I need this query to generate alist for an asp page - so I need to pass the website name as aparameter so I guess I need to make this query as a stored procedure.Does anyone know how this can be done?