Wednesday, March 7, 2012

between operator

Hi,

I'm having problems using the between operator in a query statement.

Select *
from <mytable>
where date between @.date1 and @.date2

The date values with a hour specified, aren't returned. What is the approach you would recommend here?

Thx

EDIT: by playing with this problem I've figured out I can append the hour to the date like this: <date> between @.fromDate + '00:00:00' and @.toDate + '23:59:59'

this seem to work, but I'm not sure if this is correct

Select *
from <mytable>
where date >= @.date1 and date < dateadd(d,1,@.date2)

or

Select *
from <mytable>
where date >= @.date1 and date < @.date2 +1

Denis the SQL Menace

http://sqlservercode.blogspot.com/

|||

i had a similar problem which i did through the application side:

string weekdate =txtFrom.Text;

string daydate = System.Convert.ToDateTime(txtTo.Text).Add(System.TimeSpan.FromDays(1)).ToString();

and later...

TechnicianViewInboxDataAdapter.SelectCommand.CommandText = tempselecttechnician + " where status = 1 and TechnicianID = " + Session["UserID"].ToString() + "and CallLoggedDT Between '" + weekdate + "' and '" + daydate + "' or TechnicianID = 1 and DepartmentID = 1 and status = 1 and CallLoggedDT Between '" + weekdate + "' and '" + daydate + "' or TechnicianID = 1 and status = 1 and CallLoggedDT Between '" + weekdate + "' and '" + daydate + "' and DepartmentID = " + Session["DepartmentID"].ToString();

this works as well.

the code ends up like this:

SELECT FirstName, LastName, Email, CallNumber, DepartmentName, UserName, Status, TechnicianID, CallLoggedDT, DepartmentID, CallOpenedDT, CallActionedDT, CallClosedDT FROM dbo.TechnicianInboxView where status = 1 and TechnicianID = 2and CallLoggedDT Between '2006/05/30' and '2006/06/07 12:00:00 AM' or TechnicianID = 1 and DepartmentID = 1 and status = 1 and CallLoggedDT Between '2006/05/30' and '2006/06/07 12:00:00 AM' or TechnicianID = 1 and status = 1 and CallLoggedDT Between '2006/05/30' and '2006/06/07 12:00:00 AM' and DepartmentID = 2

|||

You can also use the datediff function and the statement would look like this.

Select * from <mytable> where

datediff(dd,@.date1,<Datefield in the table>)>=0 and datediff(dd,@.date2,<Datefield in the table>)<=0

@.Date can be varchar too and it can be in the format of "mm/dd/yy" also. Need not have the time factor.

|||

where datediff(dd,@.date1,<Datefield in the table>)>=0 and datediff(dd,@.date2,<Datefield in the table>)<=0

Would not recommend doing so in the terms of performace. You will never get index seek over the index for datefield column: it will always index scan at the best.

between not betweening inclusive

In the sql statements below, both BETWEEN and (>= and <=) are giving unexpected results. I am working with monthly data where in one table the time part of [DateTime]=09:31:00 the result is correct but if the time is 16:00:00 (in another table) the statement returns empty. Also if I change either sql statement to use 16:01:00, it returns the second table correctly but that should not be necessary because both statements below are supposed to be inclusive. Anybody know why this is happening and what to do about it?

select distinct * from [clean].[table2] where

convert(varchar, [DateTime],126) between '2005-11-30' and '2005-12-01' and

convert(varchar, [DateTime],114) between '09:30:00' and '16:00:00'

order by [DateTime]

The following statement has the same problem:

select distinct * from [clean].[table2] where

(convert(varchar,[DateTime],126) >= '2006-06-05' and

convert(varchar,[DateTime],126) <= '2006-11-05') and

(convert(varchar,[DateTime],114) >= '09:30:00' and

convert(varchar,[DateTime],114) <= '16:00:00')

order by [DateTime]

Time also has a milliseconds value. It is quite likely that your time values are in actuallity greater than exactly 16:00:00 -perhaps 16:00:00.001.

If you wish to include the times that are between 16:00:00 and 16:00:01 (meaning all times with any millisecond value, then use 16:00:01.

If you wish to ignore the milliseconds value, you may be better served using the smalldatetime datatype.

|||

rwbogosian wrote:

In the sql statements below, both BETWEEN and (>= and <=) are giving unexpected results. I am working with monthly data where in one table the time part of [DateTime]=09:31:00 the result is correct but if the time is 16:00:00 (in another table) the statement returns empty. Also if I change either sql statement to use 16:01:00, it returns the second table correctly but that should not be necessary because both statements below are supposed to be inclusive. Anybody know why this is happening and what to do about it?

select distinct * from [clean].[table2] where

convert(varchar, [DateTime],126) between '2005-11-30' and '2005-12-01' and

convert(varchar, [DateTime],114) between '09:30:00' and '16:00:00'

order by [DateTime]

The following statement has the same problem:

select distinct * from [clean].[table2] where

(convert(varchar,[DateTime],126) >= '2006-06-05' and

convert(varchar,[DateTime],126) <= '2006-11-05') and

(convert(varchar,[DateTime],114) >= '09:30:00' and

convert(varchar,[DateTime],114) <= '16:00:00')

order by [DateTime]

Why cant you just use

SELECT DISTINCT
*
FROM
clean.table2
WHERE
DateTime >= '2006-06-05 09:30:00' AND DateTime <= '2006-11-05 16:00:00'
|||Your query is doing string compares, which never work with between.

You need to do this:

SELECT DISTINCT * FROM [clean].[table2] WHERE
[DateTime] between CAST('2005-11-30' AS DATETIME) AND CAST('2005-12-01' AS DATETIME) AND
CONVERT(DATETIME,CONVERT(varchar,[DateTime],114)) BETWEEN CONVERT(datetime, '09:30:00') AND CONVERT(datetime, '16:00:00')

This will convert the dates to 1900-01-01 and compare the times correctly.

There is no reason to convert the dates to strings.|||

Changing the statement to use 16:00:01 does work. The actual value in the table is 16:00:00.000 but not even 16:00:00.9999 works; it has to be a full second after the actual time in the database table.

I know in the near future I'm going to have problems when we start analyzing even smaller time frames. While I am happy that changing one second works, shouldn't BETWEEN and (<= or >=) be inclusive. Is this a bug or a feature?

|||Can't use your statement because I can't use anything before 09:30:00 or after 16:00:00 on any of the dates between (inclusive).|||Thanks Tom; that appears to be working.

BETWEEN LAPTOP AND DESKTOP

Hi,

I want to jumpstart my learning of SQL Server so I downloaded the Express edition onto my desktop in the office and also onto my laptop. I usually connect the two machines (through a LAN) to update whatever I was able to do at home while in the office.

What should I do in order to view or edit whatever I started on the laptop from the desktop? Would the databases I create on one be accessible through the other machine for editing and the likes?

Glint.

hi Glint,

you first need connectivity.. if that has to be performed at work, this is not a problem, as you just plug the office lan cable and you are on..

actually you do not need SQLExpress to be installed at all in the desktop pc as your "server" is located in the laptop.. so you just need to (remotely) connect from desktop (client) to the laptop (server)..

SQLExpress installs by default disabling network connections, so you need to run the Surface Area Configuration tool to enable "remote connections" and run SQL Server Configuration Manager to verify the desired network protocol is enabled..

you can then "connect" to your laptop server providing the appropriate credentials.. (by default SQLExpress installs allowing only WinNT authenticated connections, but you can modify that behaviour at "run time" to accept standard SQL Server authenticated connections (providing userid and password) modifying a Windows registry key,
HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer
LoginMode = 2
where MSSQL.1 identifies your "engine number".. if you only installed 1 instance MSSQL.1 should be ok... or, you can download (recommended anyway) the SQL Server Management Studio Express, the "official" GUI based management tool for SQLExpress, from http://www.microsoft.com/downloads/details.aspx?familyid=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en, and connect via a trusted connection witl administrators permissions, select the server node, access it's properties and modify the "Server authentication" properties (Security tab) to "SQL Server and Windows Authentication mode"..

but this does not "copy or sync" your laptop "databases" to the office desktop.. if you need it to (copy), you have to "detach" the database you are interested wih, copy the relative physical files to the desktop, and attach the database there (see http://msdn2.microsoft.com/en-us/library/ms190794.aspx and http://msdn2.microsoft.com/en-us/library/ms187858.aspx for further info).. the very same task can be performed via a backup+restore action.. you backup a database (full backup) on the "server", copy the backup file to the destination machine, and restore there the database, http://msdn2.microsoft.com/zh-cn/library/9st0dc24.aspx

so you have the choice to "copy" your homework to the office pc, eventually work on it and finally re-copy all to the laptop for further homeworks, or just always connect to your laptop for office work as well..

please consider downloading Books On Line (BOL), the official and primary help resource for SQL Server at http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx..

regards

|||Thanx, Andrea.

BETWEEN LAPTOP AND DESKTOP

Hi,

I want to jumpstart my learning of SQL Server so I downloaded the Express edition onto my desktop in the office and also onto my laptop. I usually connect the two machines (through a LAN) to update whatever I was able to do at home while in the office.

What should I do in order to view or edit whatever I started on the laptop from the desktop? Would the databases I create on one be accessible through the other machine for editing and the likes?

Glint.

hi Glint,

you first need connectivity.. if that has to be performed at work, this is not a problem, as you just plug the office lan cable and you are on..

actually you do not need SQLExpress to be installed at all in the desktop pc as your "server" is located in the laptop.. so you just need to (remotely) connect from desktop (client) to the laptop (server)..

SQLExpress installs by default disabling network connections, so you need to run the Surface Area Configuration tool to enable "remote connections" and run SQL Server Configuration Manager to verify the desired network protocol is enabled..

you can then "connect" to your laptop server providing the appropriate credentials.. (by default SQLExpress installs allowing only WinNT authenticated connections, but you can modify that behaviour at "run time" to accept standard SQL Server authenticated connections (providing userid and password) modifying a Windows registry key,
HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer
LoginMode = 2
where MSSQL.1 identifies your "engine number".. if you only installed 1 instance MSSQL.1 should be ok... or, you can download (recommended anyway) the SQL Server Management Studio Express, the "official" GUI based management tool for SQLExpress, from http://www.microsoft.com/downloads/details.aspx?familyid=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en, and connect via a trusted connection witl administrators permissions, select the server node, access it's properties and modify the "Server authentication" properties (Security tab) to "SQL Server and Windows Authentication mode"..

but this does not "copy or sync" your laptop "databases" to the office desktop.. if you need it to (copy), you have to "detach" the database you are interested wih, copy the relative physical files to the desktop, and attach the database there (see http://msdn2.microsoft.com/en-us/library/ms190794.aspx and http://msdn2.microsoft.com/en-us/library/ms187858.aspx for further info).. the very same task can be performed via a backup+restore action.. you backup a database (full backup) on the "server", copy the backup file to the destination machine, and restore there the database, http://msdn2.microsoft.com/zh-cn/library/9st0dc24.aspx

so you have the choice to "copy" your homework to the office pc, eventually work on it and finally re-copy all to the laptop for further homeworks, or just always connect to your laptop for office work as well..

please consider downloading Books On Line (BOL), the official and primary help resource for SQL Server at http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx..

regards

|||Thanx, Andrea.

BETWEEN keyword

I need to retrieve records where the date is in between the current date and 4 days previous.

I've tried: WHERE DateSubmitted BETWEEN GetDate() AND GetDate() - 4
it doesn't work...

Can someone help out?You are probably having problems because both the date and the time are used in such comparisons.

See if this post helps you:view post 483129

Terri|||Ok, thanks Terri.

Between Dates Query - HELP!

Hi,

I have an SQl query that will list the results if it lies between two dates, for example;

SELECT * FROM TABLE WHERE { fn Now() } BETWEEN Date1 AND Date2

This returns all results where Date1 and Date2 fall between the Current Date

What i am looking for is a way to replace the { fn Now() } with a date of my choice.

For example;

SELECT * FROM TABLE WHERE '10/10/2006' BETWEEN Date1 AND Date2

However this does not work.

Has anyone any ideas why this may be ??

Thanks in advance

Andrew Vint

try to use an sql server variable and assign it with the date u want and then put it in ur select statement

|||

Hi,

I am afraid that does not work either.

Thanks

|||

You could use a variable in the SQL query. If it didnt work for you please post the code you have.

|||Are you sure you want to put a constant on the left while 2 fields on the right? Then you have to make sure Date2 is greater than Date1, otherwise the expression will return false no matter what's the constant. Another thing you need to pay attention to is the DATEFORMAT option of current user (which can be checked using DBCC USEROPTIONS), you can useSET DATEFORMAT command to change the current date format, or always use the ODBC date format yyyy-mm-dd.|||

Hi,

Thanks for the response.

I have tried using the yyyy-mm-dd format without sucess i am afraid.

Any more ideas anyone ?

Andrew

|||

I was able to run your query without a problem on SQL 2005. The query below also runs.

SELECT * FROM myTable
WHERE cast('9/1/2006' as datetime) BETWEEN Date1 AND Date2

What are the data types for your Date1 and Date2 fields? I assume they are either datetime or smalldatetime, right? Could the problem be that they are bigint fields which store ticks instead of the actual datetime? Or are they char/varchar fields that are storing the date as a string?

Can you describe the problem you have? Do you get an error message? Do you get zero results or results that seemingly should not be returned?

|||That's really strange. It would help if we can repro your issue. Can you post some sample data from the table you're trying to query, as well as the result you expect to get, and the actual result the query returns?|||

Hi All,

Thank you for your assitance in this but after hours of staring at the same lines of query strings it has become clear that it was staring me in the face all along.

I had a date convert on the date2, because of this it was not working. As soon as i removed the convert it worked as i had expected it too.

Now before you all deservedly laugh at me please look at what i had to work with below;

strSQLHoliday = "SELECT TBL_Holidays.AgentRef, TBL_Holidays.EmpVacatID, " _
& "TBL_Agents.LastName + ', ' + TBL_Agents.FirstName AS FullName, " _
& "TBL_Teams.TeamName, CONVERT(varchar(12), TBL_Holidays.ActivityDate, 106) " _
& "AS ActDate, CONVERT(varchar(12), (DATEADD(d, CASE DATEPART(dw, ActivityDate) " _
& "WHEN 7 THEN 2 WHEN 1 THEN 1 ELSE 0 END, TBL_Holidays.ActivityDate) + " _
& "(DATEPART(dw, DATEADD(d, CASE DATEPART(dw, ActivityDate) WHEN 7 THEN " _
& "2 WHEN 1 THEN 1 ELSE 0 END, TBL_Holidays.ActivityDate)) - 2 + " _
& "CAST(TBL_Holidays.TimeTaken / (TBL_Agents.ContractHrs / 5) AS Int)) % 5 " _
& "+ (DATEPART(dw, DATEADD(d, CASE DATEPART(dw, ActivityDate) WHEN 7 THEN " _
& "2 WHEN 1 THEN 1 ELSE 0 END, TBL_Holidays.ActivityDate)) - 2 + " _
& "CAST(TBL_Holidays.TimeTaken / (TBL_Agents.ContractHrs / 5) AS Int)) " _
& "/ 5 * 7) - (DATEPART(dw, DATEADD(d, CASE DATEPART(dw, ActivityDate) " _
& "WHEN 7 THEN 2 WHEN 1 THEN 1 ELSE 0 END, TBL_Holidays.ActivityDate)) " _
& "- 2), 106) AS ReturnDate, TBL_Agents.ContractHrs / 5 AS DailyHrs, " _
& "TBL_Holidays.TimeTaken, TBL_Holidays.TimeTaken / (TBL_Agents.ContractHrs " _
& "/ 5) AS DaysTaken, TBL_Holidays.Status, TBL_Holidays.TheNote FROM " _
& "TBL_Holidays INNER JOIN TBL_Agents ON TBL_Holidays.AgentRef = " _
& "TBL_Agents.AgentRef INNER JOIN TBL_TeamsTracker ON TBL_Agents.AgentRef = " _
& "TBL_TeamsTracker.AgentRef INNER JOIN TBL_Teams ON TBL_TeamsTracker.TeamRef " _
& "= TBL_Teams.TeamRef WHERE (TBL_TeamsTracker.EndDate IS NULL) AND " _
& "('" & ChosenDate & "' BETWEEN TBL_Holidays.ActivityDate AND (DATEADD(d, CASE " _
& "DATEPART(dw, ActivityDate) WHEN 7 THEN 2 WHEN 1 THEN 1 ELSE 0 END, " _
& "TBL_Holidays.ActivityDate) + (DATEPART(dw, DATEADD(d, CASE DATEPART(dw, " _
& "ActivityDate) WHEN 7 THEN 2 WHEN 1 THEN 1 ELSE 0 END, " _
& "TBL_Holidays.ActivityDate)) - 2 + CAST(TBL_Holidays.TimeTaken / " _
& "(TBL_Agents.ContractHrs / 5) AS Int)) % 5 + (DATEPART(dw, DATEADD(d, " _
& "CASE DATEPART(dw, ActivityDate) WHEN 7 THEN 2 WHEN 1 THEN 1 ELSE 0 END, " _
& "TBL_Holidays.ActivityDate)) - 2 + CAST(TBL_Holidays.TimeTaken / " _
& "(TBL_Agents.ContractHrs / 5) AS Int)) / 5 * 7) - (DATEPART(dw, " _
& "DATEADD(d, CASE DATEPART(dw, ActivityDate) WHEN 7 THEN 2 WHEN 1 THEN 1 " _
& "ELSE 0 END, TBL_Holidays.ActivityDate)) - 2)) AND " _
& "(TBL_Agents.Location = N'" & lblLocation.Text & "') " _
& "ORDER BY TBL_Holidays.ActivityDate DESC, TBL_Agents.LastName, " _
& "TBL_Holidays.Status"

I thank you all for taking the time to assist me with this matter, your comments did make me look more closely and as a result stumble across the solution.

I have now come to the conlcusion that 10 cups of coffee are no substitute for a good nights sleep when trying to code stuff :)

Thanks Again

Andrew

between dates and times

Hello,
I am new to SQL and am having a problem with dates and times.
I have a table with a 4 columns. Date, Time, Material, Qty
example;
01/12/05 04:00 steel 35
01/12/05 06:00 steel 60
01/12/05 23:40 steel 40
01/12/05 08:00 iron 25
02/12/05 05:00 steel 20
02/12/05 06:00 steel 50
I want to be able to look for matching rows that have a start & end date and
start & end time.
i.e start date 01/12/05 time >= 06:00
end date 02/12/05 time <= 05:59
The times are aways static. I ideally would like to see one row returned tha
t
summed the last column and combined the different dates like;
01/12/05 steel 120
01/12/05 iron 25
however if I searched for 01/12/05 and 03/12/05 I would see;
01/12/05 steel 120
01/12/05 iron 25
02/12/05 steel 50
Any help or guidance will be appreciated.What are the datatypes of the date and time columns. The ideal solution
would be to represent them as a single datetime value.
In any case, as a short term solution, check out the CONVERT function in SQL
Server Books Onlne. There are arguments that can help you convert a datetime
value to date-only string and a time-only string.
Anith