Optimal Search For The Nearest Date

Nov 23, 2005

I have the following table

CREATE TABLE Readings
(
ReadingTime DATETIME NOT NULL DEFAULT(GETDATE()) PRIMARY KEY,
Reading int NOT NULL
)

INSERT INTO Readings (ReadingTime, Reading) VALUES ('20050101', 1)
INSERT INTO Readings (ReadingTime, Reading) VALUES ('20050201', 12)
INSERT INTO Readings (ReadingTime, Reading) VALUES ('20050301', 15)
INSERT INTO Readings (ReadingTime, Reading) VALUES ('20050401', 31)
INSERT INTO Readings (ReadingTime, Reading) VALUES ('20050801', 51)
INSERT INTO Readings (ReadingTime, Reading) VALUES ('20051101', 106)
GO

-- list the table
SELECT ReadingTime, Reading FROM Readings
GO


It is a table of readings of a free-running counter that is
time-stamped. I need to determine the value of the reading that
corresponds to the closest date to the supplied date

Are there more optimal/efficient ways of accomplishing this than the
following?

DECLARE @when DATETIME
SET @when = '20050505'

SELECT TOP 1 ReadingTime, Reading FROM Readings
ORDER BY abs(DATEDIFF(minute, ReadingTime, @when))

The above gives me the desired result of ('20050401', 31).


Any suggestions would be appreciated

View 1 Replies


ADVERTISEMENT

List By Nearest Date?

Oct 7, 2006

Hi, I'm making a birthdays database where I want to list everyone in it ordered by the firstcoming birthdays according to the current date.

I have all the birthday records stored in a table called bursdager and the person name is stored in the navn column and the persons birthday date is stored in the dato column.

I'm having some problems, currently I have this statement:


Code:


DECLARE @tbl TABLE (navn VARCHAR(60), dato DATETIME)


INSERT INTO @tbl
SELECT navn, dato FROM bursdager
WHERE DATEPART(month, dato) >= DATEPART(month, getdate())
ORDER BY DATEPART(month, dato), DATEPART(day, dato)


INSERT INTO @tbl -- those are the one who allready have had birthday this year
SELECT navn, dato FROM bursdager
WHERE DATEPART(month, dato) < DATEPART(month, getdate())
ORDER BY DATEPART(month, dato), DATEPART(day, dato)



SELECT * FROM @tbl





It works *allmost* as it should-- except, it still lists the last persons who had birthday first, even the days after their birthday if the month is still the same.

I thought about adding an additional check:
Code:

AND DATEPART(day, dato) >= DATEPART(day, getdate())

in the WHERE clause of the SELECT statement but that won't be correct either because it then just lists everyone based on whether the day number the person was born is higher or less than the day number of the current date.

Anyone have any suggestions? Is there an easier way to do it?

Dag

View 7 Replies View Related

T-SQL (SS2K8) :: How To Round A Date To The Nearest Second

Sep 8, 2014

how to round a datetime variable to the nearest second. The solution must NOT just strip off the milliseconds, it needs to round.

Also, the solution should not be too cumbersome because it will be used in a high volume environment.

View 5 Replies View Related

Find Nearest Date Record Without Cross Apply

Oct 13, 2012

Table :

ChangeID ChangeDate EquipmentID ModuleID EquipStatus
1 12/9/08 230 1789 Normal
2 13/9/08 450 1245 Normal
3 17/9/08 230 1789 Open
4 21/9/08 230 1899 Open
5 21/9/08 450 1674 Normal
6 22/9/08 450 2364 Normal

Given a date, what module was each equipment item in on that date?How do I get the date of the nearest previous event from a list like this? I got a query from one of the post in this Forum only using Cross Apply to find the nearest record from the above table based on Date i.e.

SELECT outerT.*
FROM your_table AS outerT
CROSS APPLY
(
SELECT TOP 1
equipment_id
, change_date
FROM your_table AS innerT
WHERE innerT.change_date <= @point_in_time
AND innerT.equipment_id = outerT.equipment_id
ORDER BY change_date DESC
) AS applicable_records
WHERE applicable_records.change_date = outerT.change_date

The problem is I need to get this query without using Cross Apply as i need to use the same for the LINQ which doesn't support Cross Apply.

View 1 Replies View Related

T-SQL (SS2K8) :: Date Comparison In Two Table By Returning Nearest Date Of Table A In Table B

Jun 9, 2014

I am having a problem in creating query for this exciting scenario.

Table A

ID ItemQtyCreatedDatetime
W001 CB112014-06-03 20:30:48.000
W002 CB112014-06-04 01:30:48.000

Table B

IDItemQtyCreatedDatetime
A001 CB112014-06-03 19:05:48.000
A002 CB112014-06-03 20:05:48.000
A003 CB112014-06-03 21:05:48.000
A004 CB112014-06-04 01:05:48.000
A005 CB112014-06-04 02:05:48.000

I would like to return the nearest date of Table B in my table like for

ID W001 in table B should return ID A002 CreatedDatetime: 2014-06-03 20:05:48.000
ID W002 in table B should return ID A004 CreatedDatetime: 2014-06-04 01:05:48.000

View 3 Replies View Related

Optimal SQL

Jul 23, 2005

Please excuse what is probably a no-brainer, but here goes.Is there any difference, in terms of performance or any other pertinentfactor, between:SELECT * FROM tblCustomers INNER JOIN tblCustomerOrders ONtblCustomers.fldCustomerID = tblCustomerOrders.fldCustomerIDandSELECT * FROM tblCustomers, tblCustomerOrders WHEREtblCustomers.fldCustomerID = tblCustomerOrders.fldCustomerIDI note that if I type the latter into the SQL pane in a Data window,SQL Server replaces it with the former.TIAEdward--The reading group's reading group:http://www.bookgroup.org.uk

View 3 Replies View Related

Optimal Database Design

Mar 2, 2005

What is more efficient for a database design - a lot of tables with only a few records or a few tables with lots of records.

I'm starting a new site and each user will have numerous records but I'm not sure whether to have a few very large tables (over 100,000 rows) or start a new table for each user which would result in approx 1500 tables most of which would be the same table design with different rows.

I'm using SQL2000.

I guess this is quite a basic question, but I'm a bit unsure.

Any references anyone could point me too as well.

Thx

View 3 Replies View Related

Optimal Installation On Win 2003

Feb 3, 2004

Hi

I'm fairly new to this, so bare with me...

I have to make a new installation of an MS SQL 2000 EE on a Windows 2003 Std. Edt.

HW:
---------------------
Dual Xeon 2,4 + 1 GB Ecc
1 x 32 MB Adaptec 2100S RAID Controller
2 x 18 GB 10K HD
4 x 18 GB 15K HD
---------------------

So far I have made following configuration....
---------------------
2 x 18 GB 10K HD / RAID 1
- C:OS
- D:MSSQL program files + System DB's (Master, pubs ect.)

4 x 18 GB 15K HD / RAID 5
- E:TempDB
- F:Data + Logs
---------------------
But I'm not sure that this is the optimal configuration, and I'm willing to start all over :)


So my q's are.......
--------------------
Which RAID configuration would you suggest?
Which partitions on the raids would you suggest?
Which usage would you assign the various partitions?
How do I move the system and temp db's?
--------------------


Thanx!

Regards,

Taras Bredel dk

View 3 Replies View Related

Search By Date

Jan 6, 2005

when i use enterprise manager, I type the following code to retrieve the date, can you check ?


SELECT *
FROM Table
WHERE (ExpirationDate BETWEEN 11 / 1 / 2004 AND 2 / 1 / 2005)

Thanks.

View 5 Replies View Related

Optimal Solution For Getting Timestamp Of Last Entry

Jul 25, 2007

Hi

I'm trying to find the optimal way of getting the timestamp of the last updated entry in an mssql database. A database is updated only about 5 times a minute, how ever a request for the time of the last entry could be around 1 per second. For this reason i was thinking of having a separate table which has a single row which is updated everytime a new entry is updated in the main table. I would then only need a simple SELECT statement and need very little processing power.

Is this the best method, or can you think of any others i could use?

many thanks

View 14 Replies View Related

100% Buffer Cache Hit Ratio Not Always Optimal?

Jun 19, 2008

I am wondering if 100% buffer cache hit ratio is considered not good in general?

Are there instances that it is actually bad and can contribute to server performance degradation?

Any thoughts on the topic most welcome :)


--------------------
keeping it simple...

View 11 Replies View Related

Optimal Configuration For Report Generator

Jul 23, 2005

I am working with a report generator that is based on SQL Server 2000 anduses ASP as the UI. Basically we have a set of reports that end users canexecute through a web browser. In general the model works fine, but we arerunning into some scaling issues.What I'm trying to determine is, what is the optimal configuration for thissystem. It is currently a 2.4G Pentium with a large RAID and 1G of RAM. Wehave been using the "fixed" memory configuration, allocating 864M to SQL.This is on a Windows 2003 server box.This works fine when a "small" query or two is executed, but the performancesuffers terribly when several users try to run reports in parallel. A singlequery might take 10 minutes to run if nothing else is happening on the box,but if additional users log on an run reports, it's almost impossible topredict when the queries will finish.I am also looking at the effect of database size on performance, runningtests against a database with 1 month, 3 months, and say 12 months of data,running the same query against 2 databases in parallel. With the originalconfiguration, the results were all over the place, with the 12 monthdatabase outperforming the smaller dbs, while other times there was littledifference. It seems that once the system starts paging, and paging heavily,it's over; the system never "recovers" and queries that previously ran in afew minutes now take hours.I added 3 G more memory to the system, and modified boot.ini to include the/3GB switch. Now when I run the same tests, the results are much moreconsistent, as the system rarely ever has to swap. Then again I've neverseen it go past 1.7G in Task manager, making me think that any more than say2.5G of memory is a waste?Things we are trying to determine are:- in the SQL Server memory configuration, is Fixed better than Dynamic? Wehave read that Dynamic is not good at returning memory to the OS once it'sbeen allocated- What else can we do to optimize the performance for this application? Itseems to me if the indexes are properly designed, the database sizeshouldn't have that much impact on performance, but this appears to be trueonly to a point. In comparing the execution plans between say a 12 month anda 3 month database, the plans are sometimes dramatically different. I assumethis is due to the optimizer deciding that going directly to the base tablesand not using an index will result in better performance, when in reality,this doesn't always appear to be true.- Are there other SQL Server switches I should be tweaking? Is there somenumber of simultaneous queries that this configuration should be limited to?- What about other versions of SQL Server (e.g. Enterprise, Data Center,etc) would these buy us anything?Thanks for any advice,-Gary

View 2 Replies View Related

What Is The Optimal Configuration For A Multicore System?

May 14, 2007



I would like to know what options are available from BIOS / OS / SQL and server perspective when configuring or tuning a system with SQL Server 2000 or SQL Server 2005.



For example, I have a system with 4 dual-core Opteron CPUs on Windows 2003 Enterprise Edition. However, the OS sees 8 CPUs -- is this the optimal configuration or is it better (if even possible) to configure the system to see only 4 CPUs? The reason for this concern is due to performance problems faced deploying systems with Hyperthreading Technology.



Any documentation or examples in this regard would be very useful. Basically, what are the scenarios that would require a certain type of CPU configuration over another.



Thanks in advance for your help,



Ziggy

View 1 Replies View Related

File Placement For Optimal Performance?

Aug 24, 2007

What is the best performance for this configuration:

Files:
Data
Log
Indexes
tempdb


Disk:
A - RAID 10
B - RAID 10 (or should this be RAID 1?)

Whats best?:
A - Data and Indexes
B - tempdb and Log

??? Thanks.

View 1 Replies View Related

Date Search Problem

Sep 27, 2006

Hi,I have a application that I’m trying to do a search in a SQL database with a dateI can add, update or delete the date but when I do a search it doesn’t work. I did a store procedure to do the search and its working but it’s only working when I pass the parameter between quote like that ‘09/15/2006’ if I remove the quote it doesn’t work  How do I configure my store procedure to automatically put the quote?OrHow do I configure my vb.net code to automatically add the quote? Thanks in advance Soft

View 6 Replies View Related

How To Search For A Date In Sql Server?

Mar 5, 2008

Hi guys,
Am developing an application where I store the date in the database. I would like to search the date from the database table. Can anyone tell me how would the search string would look like?
The current string am using is: select Pid "ID", PName "Name", Address, DateOfBirth "Date Of Birth", Phone, emergencyContact "Emergency Contact", RegistrationDate "Registration Date", DischargeDate "Discharge Date" from patient_177681 Where RegistrationDate Like '%2005-3-4%'
But this string does not return any results and so does any other data in the Like % % string. Can anyone let me know how to compare two dates and return a result? Is there any in-built function to do this?

View 2 Replies View Related

Help Simple Search Date

Mar 28, 2008

hello I have this code Select Waste.WasteName AS [Waste Name], InvoiceDetail.Volume, Branch.BranchLocation AS [Branch Location] From InvoiceHeader INNER JOIN InvoiceDetail ON InvoiceHeader.InvoiceNo = InvoiceDetail.InvoiceNo INNER JOIN Waste ON InvoiceDetail.WasteID = Waste.WasteID INNER JOIN Branch ON InvoiceDetail.BranchID = Branch.BranchID Where WasteName = 'Sludge' AND InvoiceDate >= '" + TextBox1.Text + "' AND InvoiceDate <= '" + TextBox2.Text +  "'; The problem is everytime I will search for example InvoiceDate 03/27/2008, I need to add one day for example --> 03/28/2008 for me to be  able to get that Invoicedate 03/27/2008.. What's do you think is the problem with my code?  Thanks!  

View 9 Replies View Related

Search Parameter By Date

Oct 20, 2006

Hello guys I hope everyone is doing well I have a question. I have a database thats an ADP. on one of the forms I have a command button that has a stored procedure in it that will allow them to search by TM# or name or whatever, (I have the code below) I would like them to be able to do the samething but by date rather then TM# or Name, how would I go about doing that with a datetime datatype??

thank you

ALTER PROCEDURE dbo.Search_ActiveConditionals
(@Enter_TM# int)
AS SELECT TM#, LASTNAME, FIRSTNAME, CONDITIONAL, DATEOFCONDITIONAL, INVESTIGATOR_COND, REASONFORCOND
FROM dbo.ACTIVE_CONDITIONALS
WHERE (TM# = @Enter_TM#)

View 2 Replies View Related

Date Format For Search

Jul 3, 2007

hi
i am using a calendar control. the format is mm-dd-yyyy

my table stores date in the following format-
mm/dd/yyyy hh:mm:ss

my search is based only on date(not time). how can i do it?


thanks
Jaimin

View 4 Replies View Related

SQL 2012 :: Optimal Settings For DBCC Checks?

Aug 5, 2014

I have a VM set up for offloading DBCC checks. Specs are below. I've read through this, but I'm not seeing the performance gains by enabling the trace flags and using the physical only switch.

Is the whole drawback that I'm on SATA storage? Is there a VM configuration with the CPU I can/should change? I've been playing with MAXDOP trying to see if I can get any benefits but I'm not seeing a much.

wait_type wait_time_spctrunning_pct
CXPACKET 561191.4228.7128.71
OLEDB 387136.7619.8148.52
PAGEIOLATCH_SH 340674.5817.4365.95
TRACEWRITE 321598.8416.4682.41

[code].....

View 9 Replies View Related

Nearest Distance

Jan 21, 2004

Hi
How do I get a nearest distance of a point? For example, I have two tables A and B and I want to find the nearest distance between the records of the two tables. In addition, one of the tables should also give me the distance. The data I have geo spatial data. Can this be done in SQL
Help will be appreciated

View 12 Replies View Related

Search For A Specific Date When Specified As String?

May 18, 2007

Dear all
 
I am pretty new to SQL server 2005 and have the following issue:
I get the date from the asp applciation in format dd/mm/yyyy and then try to do a search for all records that might match that date in sql server 2005. The date is storred in ther database in datetime format.
I am having trouble composing the stored procedure to do that.
Any help would be apreciated.
Sincerely
d

View 2 Replies View Related

Problem With Date Search Plz Help Me Quickly

Oct 22, 2007

I am trying to search for stored files "for example from date: 15/12/2003 to: 24/6/2006" and when i press search no results appeare the following is the database code:
1    public DataTable searchData(string fileNo, string Title, string dFrom, string dTo, string brief)2        {3            string str = "";4    5            str = "select * from Tb_File where Active = 1 ";6    7            if (fileNo != "")8                str += " and FileNo='" + fileNo + "'";9            if (Title != "")10               str += " and Title like '%" + Title + "%' ";11           if (brief != "")12               str += " and Brief like '%" + brief + "%' ";13           if (dFrom != "")14               str += " and DFrom >= convert(datetime,'" + Convert.ToDateTime(dFrom).ToShortDateString() + "',103) ";15           if (dTo != "")16               str += " and DTo < convert(datetime,'" + Convert.ToDateTime(dTo).ToShortDateString() + "',103) ";17   18           ole.Open();19           SqlDataAdapter DA = new SqlDataAdapter(str, ole);20           DataTable DT = new DataTable();21           DA.Fill(DT);22           ole.Close();23           return DT;24   25       }
 i am using sql 2000, with Visual Studio 2005.
 
 

View 14 Replies View Related

Search Record Base On Date

Oct 27, 2000

Hi,

The following is a VB code which I use it to check the existence of the record before I insert a new record
into my SQL 7.0 database. When I run the vb code, I got an error which is
"-2147217913 [Microsoft][ODBC SQL Server Driver][SQL Server]The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value." I couldn't figure out what's wrong with my code especially the WHERE clause.
Please help me look into this problem. TQ.

Private Sub AddDate()
Dim rstDate As ADODB.Recordset
Dim myDate As Date
Dim Criteria As String

myFileDate=#27-10-2000 16:00#
myDate = Format(myFileDate, "mm-dd-yyyy")

Criteria = "SELECT Date " _
& "FROM DateGen " _
& "WHERE Date = '" & myDate & "'"

Set rstDate = New ADODB.Recordset

With rstDate
.ActiveConnection = cn
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.Open Criteria
End With

If rstDate.RecordCount > 0 Then
RecordExist = True
Else
RecordExist = False
rstDate.AddNew
rstDate("Date") = Format(myFileDate, "dd-mm-yyyy")
rstDate.Update
End If
rstDate.Close
End Sub

Regards,
May

View 1 Replies View Related

Search In Table For Date-time?

Feb 28, 2001

Hi,

Dow do I search for a dat time in table like
select * from table where colDate = '1999-09-09+00:00:00.000'. This doesn't work so how to go abt it?

View 2 Replies View Related

SQL 2012 :: Optimal Combination Of Tools For Flexible Reports

May 28, 2014

I would like to build a report with nice functionalities like filter, sorting, drill-down, something like a PowerPivot Table, but with some layout/design/format capabilities. I would also want to publish the report, refresh it let´s say once a week, notify users when a new version is available, etc.

If I use PowerPivot, then I am not able to customized the report or to mix data from different sources in one table.

If I convert the cells of the PowerPivot table to workbook formulas I lose the filter, sorting, etc functionalities.

I still have to try using Reporting Services, but I think that always something is missing.

View 1 Replies View Related

Need An Optimal Way To Merge External Dataset To Database Values

Jan 3, 2008

C# .Net Application as front end
Sql Server2000 as back end

I need to merge an external dataset from .Net app(in XML format) with the information in database with one column in database table as the merging criteria. A situation similar to Left Outer Join, wherein i need all records from external dataset and if matched in database the corresponding values from there too, the only difference here is that the join is not between two Tables its between a table and external dataset.
There is no need to store the external dataset in the database in persistent form, its just a query - merge - response operation.

So, can anyone suggest the best possible solution for this? A table variable / temporary table / some other schema, what and how?

Thanks in advance..

View 8 Replies View Related

T-SQL (SS2K8) :: Round Value To The Nearest

Sep 16, 2014

I have a column called as NDM$ What I want do it round it the nearest value example I am giving below

34.100->34%

39.8->40

35.4->35 some thing like that.

View 6 Replies View Related

Round To Nearest WHOLE Number

Nov 16, 2006

T-SQL:How to round to the nearest WHOLE number ?sofrom -- to-------------170 --17096.58 --97thanks

View 1 Replies View Related

Rounding To The Nearest Thousand

May 11, 2007

Hi

Which parameter value for the Round function do I need to pass to get it to round to the nearest thousand ?

Thanks,
Neil

View 7 Replies View Related

Search By Multiple Date Range Options

Nov 1, 2007

I inherited a system and am moving our SQL2000 input data into a new 2005 database for web searching by clients. The conversion went pretty well, but I'm looking for suggestions on how best to index and query the data.



Details: We have almost 500,000 records in a pretty wide history table, and will be adding more records daily. The original table design has numerous sets of dates(first/last of different types), some small fields, and one large text field that is used for full-text catalog. The input dates are all stored as datetimes set to midnight by an insert trigger.


...

FirstPub as datetime

LastPub as datetime

FirstSale as datetime

LastSale as datetime

Name as varchar(50)

Addr as varchar(50)

DetailText as text....



I need to create a new asp.net page that can accept any specific date, or a range of dates (first/last publish date or range, first/last sale date or range) along with any of the optional 10 text fields. All input is optional, and any combination of fields can be entered. Result set has to include the primary key, key dates, and the large text field.


I've read many posts and articles, but find many different opinions about what works best. I found a similar solution that used a series of case statements with text operators indicating if the date was input or not. Other guys say no - just pass the dates as null without any additional control fields.



I found solutions saying it's best to pass dates as strings, and others that say to use datetime everywhere and just format the presentation. Some say convert dates to formatted dates and then compare them. Others say that causes table scans and should be avoided.



Questions:

1) What is the best way to get a compare dates that are entered through an asp.net page and stored procedures?

2) How to query either a specific date, as well as a range between the first and last date specified? Can it be done efficiently without needing additional screen fields for the range specification? If tried checking nulls, but am having trouble selecting multiple sets of date ranges and/or specific dates with one proc. There is always the old method of storing the selected keys in temp table, and then returning the distinct rows. Most of my experience has been in SQL 7.0 and some 2000, so I'm wondering if there are new ways to tackle the problem.

3) Better to create an index for each date type that might be selected, or one index that has all the main dates in one place?

4) Should we split the large text field to another table in our search database? It would seem to make sense to split them as we add records from the input system. Two tables linked with the same primary key seems like a good improvement from original table design. How would that affect the performance of returning all selected rows and including the large text field?

View 3 Replies View Related

Help- Search In Long Date Format 05/05/2008 14:51:03

May 5, 2008

hi need help search in long date format
i have table like this
need to search date + time + minute
no second !
only date + time + minute no second

SELECT *
FROM tb_tb
WHERE (dateinb = CONVERT(DATETIME, '2008-05-05 14:58, 102))

dateinb
---------------------------

05/05/2008 14:51:03
05/05/2008 14:51:03
05/05/2008 14:51:03
05/05/2008 14:51:03
05/05/2008 14:53:03
05/05/2008 14:53:03
05/05/2008 14:53:03
05/05/2008 14:53:03
05/05/2008 14:56:03
05/05/2008 14:56:03
05/05/2008 14:56:03
05/05/2008 14:56:03
05/05/2008 14:58:09
05/05/2008 14:58:09
05/05/2008 14:58:09
05/05/2008 14:58:09


TNX

View 4 Replies View Related

What Is The Optimal Solution To Find, If All The Data Is Entered On A Predefined Condition?

Dec 10, 2006

Hi,I want to know the optimal solution, to find if all the data was entered. Lets say, Table A (date field) and for a given month, i need that all the days in the given month are present in the Table A. Right now i have different solutions, 1) a stored procedure which loops through all the days in the given month against a select statement on Table A2) a stored procedure, create a temp table which contains all the dates in the given month, and a single select statement using where condition (select * from.... where datefield not in (select * from...))I want to know what is the best solution of these two or any other solution.Thanks 

View 9 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved