Selecting date value without time in SQL Server 2005 - sql-server

I am facing a problem selecting the date in SQL Server 2005. The table name is Softskill and the column name is insertdate. The data is stored as 2011-09-22 08:50:28.000 in this format.
To select, I am passing values from the front end as '2011-09-22', I mean the date only.
I tried to use
SELECT INSERTDATE FROM SOFTSKILL WHERE INSERTDATE = '2011-09-22'.
But it is not showing the record. May I know which format the column is following and is there any way to retrieve data by using only date?

You want to search for a range of times that encompass the day. Something like:
SELECT INSERTDATE
FROM SOFTSKILL
WHERE INSERTDATE >= '2011-09-22 00:00:00'
AND INSERTDATE < '2011-09-23 00:00:00'
You could also apply functions to INSERTDATE to extract just the date portion, but that will make the query nonsargable.

SELECT *
FROM SOFTSKILL
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, InsertDate)) = '2011-09-22'

This will do what you need
SELECT INSERTDATE
FROM SOFTSKILL
WHERE CAST(FLOOR(CAST(INSERTDATE AS FLOAT)) AS DATETIME) = '2011-09-30'
You need to truncate INSERTDATE so its time part is 00:00:00.000; then, it will be equal to '2011-09-30' assuming INSERTDATE is '2011-09-30 XX:XX:XX.xxx'.

Related

can we use if condition for compare 2 dates and display the row in sql server

I have 2 dates column, one is current date and the one is user define date, I have to display the specific row when the user define date is 2days greater than current date.
In the below code I try to display the row, when both dates are equal. But I don't know how display the row in sql.
I have following Columns,
Rid
DateTime (User define date and time)
Reminder
Description
CRDateTime (current date and time)
I have to set 3 condition.
if both dates are equal means that should be display,
if DateTime is 2 days before CRDate means I have to display that row,
if DateTime is 1 day before the CRdate means I have to display that row.
declare DateTime as datetime1;
select RId if CAST (DateTime as date) =CAST (#CRDateTime as date)
The IF...ELSE statement is a control-flow statement that allows you to execute or skip a statement block based on a specified condition.
For example:
IF Boolean_expression
BEGIN
-- Statement block executes when the Boolean expression is TRUE
END
ELSE
BEGIN
-- Statement block executes when the Boolean expression is FALSE
END
If you want to check something in your SQL Statements you should use the where clause.
It could be looking like:
SELECT * FROM `[YOUR_TABLE_NAME]` WHERE `DateTime` = `CRDateTime`
If you want to check the date in a 2 Day decade you can use the SQL DATEADD Function.
It lookse like:
SELECT DATEADD(day, +1, '2017/08/25') AS DateAdd;
Resault of this code is 2017/08/26
In your case it looks like this:
SELECT RId where DATEADD(day, +2, DateTime) = CRDateTime
--- EDIT SECTION: ---
EDIT 1:
All in one you can use this code here:
SELECT RId WHERE
`DateTime` = `CRDateTime` OR
DATEADD(day, +1, DateTime) = CRDateTime OR
DATEADD(day, +2, DateTime) = CRDateTime
As I understand you basically want to show all the records with in range of 2 days.
SELECT RId, DateTime, Reminder, Description, CRDateTime
WHERE CRDateTime BETWEEN DATETIME AND DATEADD(day, +2, DateTime)
Or you may try this
SELECT RId, DateTime, Reminder, Description, CRDateTime
WHERE DateTime BETWEEN DATEADD(day, -2, CRDateTime) AND CRDateTime
The question isn't clear. I assume the actual question is how to filter a table's rows between two dates.
Filtering in SQL (in any product) is the job of the WHERE clause, not IF. You can use the BETWEEN clause to select values in a range.
If both the table field and the query parameter are date variables, the query is easy :
CREATE TABLE table1
(
RId int PRIMARY KEY,
DateField date,
INDEX IX_Table1_Date (DateField)
)
declare #dateParam date='20190801';
SELECT RId
FROM table1
WHERE DateField BETWEEN dateadd(day,-2,#dateParam) AND #DateParam
This query will take advantage of the IX_Table1_Date index to speed up the search. Typically, applying any kind of function on a table field prevents the query engine from using any index that includes that field simply because the values stored in the index have no relation to the function's result.
If you use the date parameter to be the current date, just assign GETDATE() to it.
declare #dateParam date=GETDATE();
If the field isn't a date, you can cast it to date and still get a fast range query, because the query engine is fast enough to convert the cast to a range query.
SELECT RId
FROM table1
WHERE cast(DateField as date) BETWEEN dateadd(day,-2,#dateParam) AND #DateParam
If DateField is not a date-related type, eg it's a varchar, a) that's a serious bug and b) the server won't be able to use any indexes.
Casting the parameter values won't affect performance as they actual values are calculated before the query starts executing. The query becomes quite noisy though :
declare #dateParam datetime='20190801'
SELECT RId
FROM table1
WHERE cast(DateField as date)
BETWEEN dateadd(day,-2,cast(#dateParam as date)) AND cast(#DateParam as date)
That's why it's better to use the correct type for parameters

How can I compare a DATE value with the result of GETDATE()

I am trying to grant and revoke server roles for user id picked from a table.
I am using the following query to insert a row from master table to another table whenever the expiry date approaches, however the command is not inserting any rows into the slave table.
Insert into tbl2(userid, role, startdate, expirydate)
Select userid, role, startdate, expirydate
from tbl1
where expirydate = Dateadd(day,0, getdate())
If I use <= or >= the above query is working but that is not helpful when we have multiple rows in tbl1.
It's because GETDATE() returns a DATETIME value, and you're likely comparing it to a DATE, so you're effectively comparing values like this:
SELECT GETDATE() AS DateTimeValue,
CAST(GETDATE() AS DATE) DateValue;
Output:
DateTimeValue DateValue
2017-10-04 10:34:35.023 2017-10-04
By default, a DATE will have a time set to midnight if comparing to a DATETIME, like: 2017-10-04 00:00:00.000.
These values aren't going to be equal with a time included, so use CAST or CONVERT to get a DATE without the time:
where expirydate = Dateadd(day,0, CAST(GETDATE() AS DATE))
Although, it looks like you don't need that Dateadd on the WHERE clause, so remove it unless this is edited / sample code. So maybe edit it to this:
where expirydate = CAST(GETDATE() AS DATE)
Reference
GETDATE (Transact-SQL)
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

How to convert varchar into usable date in SQL Server?

I am having an issue converting an nvarchar into a date.
The column title is DOS and the dates are formatted like 05-03-2012.
I am trying to convert to a date so I can filter in the where clause.
I have seen explanations using CONVERT(datetime, DOS, 101) but I am not sure where this would go? In the select? In the where clause? Is this the best method to convert varchar into date?
SELECT BedSize
,avg(contributionmargin) AS ContributionMargin
FROM Summary
WHERE DOS > '06-30-2016'
GROUP BY bedsize
HAVING avg(contributionmargin) > 10000
ORDER BY contributionmargin DESC
In this example the where clause is just looking at the '06' in the date and selecting values that are greater than 06, so the results include:
07/01/2013
07/02/2009
08/31/2009
09/25/2012
11/03/2016
12/03/2008
The problem is that the years are ignored.
Option 1:
Add a new datetime column (let's suppose DOSDate) in the table and then run this query
update mytable set DOSDate = STR_TO_DATE(DOS,'%m-%d-%Y')
But future inserts in mytable will also needs to be converted and stored in DOSDate` column.
Option 2:
If you cannot add a new column, use this in where clause
select * from mytable where STR_TO_DATE(DOS,'%m-%d-%Y') > p_mydate
Since you have not provided a query, the above is a sample query to illustrate the point.
UPDATE
Initially you marked your question related to MySQL. For SQL Server you may use CAST or CONVERT instead of STR_To_DATE https://msdn.microsoft.com/en-us/library/ms187928(v=sql.90).aspx
I was able to use the convert function for SQL Server.
This code works:
SELECT BedSize
,avg(contributionmargin) AS ContributionMargin
FROM Summary
WHERE Convert(DATE, DOS, 101) > '06-30-2016'
GROUP BY bedsize
HAVING avg(contributionmargin) > 10000
ORDER BY contributionmargin DESC

Update SQL dates in SQL Server 2008

this is what I need: from the saledate column I need to extract just the month and date and combine with the 2017 year in NewDate column, but I couldn't update. Any suggestions?
This is the Select statment, I'm trying to update with the alias NewDate and getting an error: The conversion of a varchar data type to a datetime data type resulted in an out of range value.
This is the data in the saledate column: 1983-09-01 00:00:00.000, I'm trying to make to be the same, just the year to be 2017.
SELECT saledate, renewaldate,CONVERT(date,saledate), ('2017'+ '-' + LTRIM(REVERSE(SUBSTRING(REVERSE(CONVERT(date,saledate)), 1, 5)))) AS NewDate FROM tprogram
UPDATE tprogram
SET renewaldate = ('2017'+ '-' + LTRIM(REVERSE(SUBSTRING(REVERSE(CONVERT(date,saledate)), 1, 5)))) FROM tprogram
You could use dateadd() with the day() and month() functions like so:
select dateadd(day,day(saledate)-1,dateadd(month,month(saledate)-1,'20180101')) as NewDate
For example:
select dateadd(day,day(getdate())-1,dateadd(month,month(getdate())-1,'20180101'))
returns: 2018-05-16
You say you need it with the 2017 year, but you're using a 2018 value. Here's something to get started.
SELECT CONVERT(DATE,'2017-'+CONVERT(VARCHAR(2),MONTH(SaleDate))+'-'+CONVERT(VARCHAR(2),DAY(SaleDate))) AS NewDate
You can use datefromparts as below:
select SaleDate, RenewalDate, Convert(date, SaleDAte),
DATEFROMPARTS(2018, datepart(month,SaleDate),DATEPART(day,SaleDate)) as NewDate
from yourtable
Just add the difference in years back to the sale date.
SELECT DATEADD(YEAR,DATEDIFF(YEAR,SaleDate,'20170101'),SaleDate)

In SQL Server how can I split a TransactionDateTime column into two separate columns Date and Time?

Team,
I have a TransactionDateTime column with data and time information together like this - 2016-03-14 03:32:44.000.
I am looking for a Split Function in SQL server 2005 that would split this column into two separate columns one for "Date" and another for "Time" and the final output will look like this.---- Date (2016-03-14) and Time (03:32:44.000)
TransactionDateTime Date Time
2016-03-1403:32:44.000 2016-03-14 03:32:44.000
Thanks.
Declare #dateTime datetime = getDate()
SELECT
#dateTime TransactionDateTime,
CONVERT(VARCHAR(10),#dateTime,101) as [Date],
CONVERT(VARCHAR(10),#dateTime,108) as [Time]
You can typecast to date/time accordingly since the output is varchar.
This should work...
select getdate(), convert(date, getdate()), convert(varchar(10),
getdate(), 108)
Replace "getdate()" with your TransactionDateTime.
Noel

Resources