Date subtraction error - sql

I have a SQL Server table with a few columns.
One of those columns is a date and another is No of Nights.
Number of nights is always a two character varchar column with values like 1N, 2N, 3N etc depending on the number of nights up to 7N.
I want to subtract the 1 part of the 1N column from the date.
For ex: 25Oct15 - 1N = 24Oct15
Obviously I will be replacing the '1N' with the actual column name. I tried doing a trim as:
date - left(no of nights, 1)
But I get an error
Conversion failed when converting the varchar value '25Oct16' to data type int.
Sample date below
Date | NoofNIghts | Result
2016-04-26 00:00:00.000 | 1N |
2016-04-28 00:00:00.000 | 3N |
Where the result column would be the subtracted value. Any help would be great. Thanks.

SELECT DATEADD ( DAY, - CONVERT(INT, REPLACE(NoofNights, 'N', '')), getdate() ) as Result

Try this
DECLARE #V_Date DATETIME = '2016-04-26 00:00:00.000'
,#V_NoofNIghts VARCHAR(2) = '1N'
SELECT DATEADD(DAY, CAST(LEFT(#V_NoofNIghts,1) AS INT) *-1 ,#V_Date)

Well basic query should be like
Update tablename
set result= DATEADD(d, -CAST(LEFT(NoofNIghts, LEN(NoofNIghts)-1) AS INT),Date)

Related

How to delete first value in column at rest values convert to date

I have in SQL Server column "col1" where I have values like below:
col1
-----
1210607
1191011
1200101
I would like to convert this column to date column, by doing:
1210607 is 2021-06-07
1191011 is 2019-10-11
1200101 is 2020-01-01
So 1 is at the beginning of each row and it is useless, so I need to delete 1 at the beginning of each row and convert values to date format as above.
How can I do that in SQL Server?
You can add the century -- 19000000 -- then convert to a string and a date:
select convert(date, convert(varchar(255), 19000000 + col1))
Here is a db<>fiddle.

query varchar field with date values

on sql-server db i need to query the dates > getdate from a varchar field
My table is like below ( activatioDate type is varchar(100)) :
id | activatioDate
22 | 12/3/2021
23 | 12/7/2019
24 | 12/9/2020
25 | 12/3/2019
26 | 12/11/2019
27 | 12/1/2024
my query
select * from mytable
where activatioDate > GETDATE()
Expected result
22 | 12/3/2021
24 | 12/9/2020
27 | 12/1/2024
I've got the following error
"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. "
Any suggestion?
You need to fix your design; that's the real problem here. Firstly, change the values to a unambiguous date/time format:
UPDATE dbo.YourTable
SET activatioDate = CONVERT(varchar(8),CONVERT(date,activatioDate,101),120);
Then you can ALTER the table:
ALTER dbo.YourTable ALTER COLUMN activatioDate date;
And then, finally, your query will work:
SELECT *
FROM dbo.YourTable
WHERE activatioDate > GETDATE();
Use CONVERT:
SELECT *
FROM mytable
WHERE CONVERT(datetime, activatioDate, 101) > GETDATE();
But in general you should avoid storing your dates as text in your SQL database.
Find all employees who didn't make any orders in the past 6 months. Tricky thing - the date field is varchar. You need to cast it to Date and apply Date functions

Converting "42978.6736458333" varchar to datetime

I've a varchar column with a value of 42978.6736458333 that I want to convert back to a proper datetime. I've searched quite a bit and tried many of the suggestions but I cannot seem to find one that works with the data I have.
I got this value from excel when I did a CONCATENATE of all the fields in the sheet to do an insert to my DB; the output of the datetime column looks like "42978.6736458333" (the cell originally contained "2017-08-31 16:10:03"). I tried formatting and various things in excel to no avail.
Here are a few examples of what I've tried:
Select
convert(varchar(23), date, 112) DATE1,
convert(datetime, '20160805') DATE2,
convert(datetime, '2011-09-28 18:01:00', 120) DATE3,
dateadd(second, 42978.6736458333 * 24*24*60, '1899-12-31') DATE4
From
[dbo].[trainingLog]
Results:
DATE 1 = 42978.6736458333
DATE 2 = 2016-08-05 00:00:00.000
DATE 3 = 2011-09-28 18:01:00.000
DATE 4 = 1947-01-25 11:16:01.000
For every result. DATE 2/3/4 don't count up even though the original datetime varchar increments.
For example, here are more varchar values:
42981.5092361111
42982.7187615741
42983.8171527778
The above attempts return a value/date, but it's the same date even though my varchar value increments.
I expect any datetime format. I really only want the month/day/year in any format.
Try
SELECT CAST(42978.6736458333 AS DATETIME)
returns
2017-09-02 16:10:03.000
However SQL server uses 01/01/1900 as the epoch whereas your excel uses 30/12/1899 or 31/12/1899 as the epoch so it looks like you need to subtract 2 days off after you cast.
e.g.
SELECT dateadd(d, -2, CAST(42978.6736458333 AS DATETIME) )
returns
2017-08-31 16:10:03.000
From you comment I am not sure how you get your value as running
SELECT CAST(42981.5092361111 AS DATETIME)
returns for me
2017-09-05 12:13:18.000
This looks like an Excel time. So:
select dateadd(minute, 42978.6736458333 * 24*60, '1899-12-31')
If you try to use seconds, you will get an overflow error. If seconds are important, you can do:
select dateadd(day, floor(42978.6736458333), '1899-12-31') +
dateadd(second, (42978.6736458333 % 1)*24*60*60, 0)

Converting a 5 digit int into time

In a legacy system (SQL Server 2005) I have a column that stores a 5 digit integer (ie 86340) as time. The legacy application shows 86340 as 23:59:00. I am unsure how how to translate that 5 digit integer into a date-time data type using SQL.
SQL Server 2012+ has TIMEFROMPARTS function:
TIMEFROMPARTS ( hour, minute, seconds, fractions, precision )
Returns a time value for the specified time and with the specified precision.
Which is similiar to Excel's TIME:
TIME(hour, minute, second)
Excel version could handle values over 0-60 range:
Minute Required. A number from 0 to 32767 representing the minute. Any value greater than 59 will be converted to hours and minutes.
And SQL counterpart cannot do that.
It looks like that value is simply number of seconds so you could use:
DECLARE #A1 INT = 86340;
SELECT DATEADD(second, #A1,CAST('00:00:00' AS TIME));
DBFiddle Demo
EDIT:
As SQL Server 2005 does not support TIME data type, you could use DATETIME instead and skip date part in application.
DECLARE #A1 INT = 86340;
SELECT DATEADD(second, #A1,CAST('00:00:00' AS DATETIME));
DBFiddle Demo2
Since the value you have is an integer representation of the seconds since midnight, you have a couple of choices in SQL Server 2005. You can either render the value as a VARCHAR, which is readable, you can render it as DATETIME, which appends the date information, or you can maybe pull in a date from another field to get an meaningful DATETIME for your value.
SELECT CONVERT(VARCHAR(12), DATEADD(SECOND, 86340, 0), 114) AS [InVarchar];
+--------------+
| InVarchar |
+--------------+
| 23:59:00:000 |
+--------------+
SELECT DATEADD(SECOND, 86340, 0) AS [InDatetime];
+-------------------------+
| InDatetime |
+-------------------------+
| 1900-01-01 23:59:00.000 |
+-------------------------+
SELECT DATEADD(SECOND, 86340, CAST('2018-09-05' AS DATETIME)) AS [InDatetimeWithDate];
+-------------------------+
| InDatetimeWithDate |
+-------------------------+
| 2018-09-05 23:59:00.000 |
+-------------------------+
USE below query:
SELECT CONVERT(DATETIME, #Column_Name)
FROM Table;

How to convert GetDate() in 1 Jan 2014 format?

I using a query where I am selecting some attributes from the table based on a where condition. My where condition is-
date>GetDate();
I have tried this-
SELECT TOP 2 img,name,substring(description,1,80) as
description,Convert(nvarchar,date,106) as date
FROM tbl_test
where date>=Convert(nvarchar,GetDate(),106)
order by date Asc;
This query is running fine but showing different result as compared to a different query of similar kind in which I am not converting the date format.
SELECT TOP 2 img,name,substring(description,1,80) as description,date
FROM tbl_test
where date>=GetDate()
order by date Asc;
Please guide me where I am doing wrong?
Your first query will convert getdate() into nvarchar data type and it will compare date with string while 2nd query will compare 2 dates. So 2nd option is better. Still if you want to convert date into string then check then use 102 format like
WHERE CONVERT(varchar(20),date,102) >= CONVERT(varchar(20), getdate(),102)
For select column you can use format which you want like
SELECT CONVERT(varchar(20),date,106)
Final Query is :
SELECT TOP 2
img,
name,
SUBSTRING(description,1,80) as description,
CONVERT(varchar(20),date,106) as [DisplayDate]
FROM tbl_test
WHERE CONVERT(varchar(20),date,102) >= CONVERT(varchar(20), getdate(),102)
ORDER BY date ASC;
Without convert to varchar, you can cast getdate() to date to remove time part :
SELECT TOP 2
img,
name,
SUBSTRING(description,1,80) as description,
CONVERT(varchar(20),date,106) as [DisplayDate]
FROM tbl_test
WHERE date >= CAST(getdate() as date)
ORDER BY date ASC;
SQL Fiddle Demo
DECLARE #Date Datetime;
SET #Date = GETDATE();
SELECT CONVERT(VARCHAR(12), #Date, 113) AS Date
RESULT
╔══════════════╗
║ Date ║
╠══════════════╣
║ 01 Jan 2014 ║
╚══════════════╝
Edit
as Upendra Chaudhari has explained that when you do comparing column Date with a string =Convert(varchar(20),GetDate(),102),
what is actually happening behind the scenes is Convert(varchar(20),GetDate(),102) returns a string 2014.01.01 but to compare this string with a Datetime column SQL Server does an implicit conversion to compare both values. Sql Server have to have both values in the same datatype to compare them.
Now datatype Datetime has Precedence over nvarchar/varchar datatype so sql server converts the string into datetime datatype which returns something like
SELECT CAST('2014.01.01' AS DATETIME)
Result : 2014-01-01 00:00:00.000
Now in this process of converting your values to string and then back to datetime you have actually lost all the time values in your comparing values. and this is the reason why you are getting unexpected results back.
so make sure whenever you are comparing to have exactly the same datatype on both sides and take control of any data conversions in your code rather then sql server doing datatype conversions for you.
I hope this will explain you why you are getting different results .
You may try:
where date>=CONVERT(VARCHAR(11), GETDATE(), 113)