Importing date column ends in error - sql-server

While i try to upload a flatfile which contains date fields with data type DATE in ssms import/export wizard throws an error like below
Conversion failed when converting date and/or time from character string
Actual data in flat file
Period
12/17/2003
01/01/0001
10/25/2001
01/01/0001
Please help me how to upload those dates ..... i know error which lies in fileds which contains '01/01/0001' but it is business logic i cant able to change those data.... !!!
Thanks in advance

In your case, One possibility to convert the Date in integer(37972) to DATETIME after the insertion is by using dateadd.
Run the below query, after you Insert the values into VARCHAR type column.
UPDATE YourTableName
SET ColumnWithVarcharType = CAST(DATEADD(d,
CAST(ColumnWithVarcharType AS INT), -2) AS VARCHAR(20))
WHERE IsNumeric(ColumnWithVarcharType) = 1
Above query will update only the selected values having integer(37972) value. It won't care about values like '01/01/0001'.
SELECT DATEADD(d, 0, 0) => 1/1/1900
SELECT DATEADD(d, 37972, -2) => 12/17/2003
by default the DB return the initial date used in the sql server for the query SELECT DATEADD(d, 0, 0). In the same way you can add the 37972 to the Initial date like SELECT DATEADD(d, 37972, -2).

Try using ISDATE function which will tell you whether the given date is Valid or not.
SELECT CASE
WHEN Isdate('10/25/2001') = 1 THEN CONVERT(varchar(20), '10/25/2001',102 )
ELSE NULL
END

The problem is with your input value: => 01/01/0001
Immediate Workaround i can suggest is change your datatype in table from datetime to date
select cast('01/01/0001' as date)
or
select convert(date,'01/01/0001')
Output: 0001-01-01
select cast('01/01/0001' as datetime)
or
select convert(datetime,'01/01/0001')
Output: Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Related

I want to select the latest 7 days of data using the Time column

I have a SQL SERVER Table with Time and other columns. The data coming in the Time column as Dec 23 2019 7:13PM
I want to select the latest 7 days of data using the Time column. I tried below but no luck and getting an error.
Query:
Select [SQL Instance]
,[Database]
,[Target Login Name], [Time] from [dbo].[SQLLoginsAlerts] where Time >= SELECT DATEADD(day,-7,GETDATE());
Error:
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
Column information:
DATA TYPE: nvarchar(50)
How data is coming into the column:
e.g:
declare #Time nvarchar(50)
SET #Time = GETDATE()
INSERT INTO (#Time)
SQL Server is pretty good about converting date/time values with no format string. So this should work:
where convert(datetime, Time) >= DATEADD(day, -7, GETDATE())
The caveat is that you might have bad values in the data. To prevent problems with that, use try_convert():
where try_convert(datetime, Time) >= DATEADD(day, -7, GETDATE())
You can see the bad values by using:
select time
from SQLLoginsAlerts
where try_convert(datetime, time) is null and time is not null;
And after all this, fix your data! Do not store date/time values as strings. The built-in data types are there for a reason.

How to add 1 day from a user defined date in SQL?

What I understood in SQL is if you add 1 day from today's date, you can use
SELECT #date = CONVERT(VARCHAR(8), DATEADD(DAY, 1, GETDATE()), 112)
but my issue is, I am not getting today's date. I have a user defined field for date which I was the one who set this date.
Example: my column is name is "Return Booked", how shall I add 1 day to every return booked I have set?
See attached: SQL Server result
Also, if I try to use CONVERT (DATEADD, *****) I have an error below:
How to deal with the error: Conversion failed when converting date and/or time from character string.
My current SELECT statement is
SELECT dbo.AdditionalDetailInfo.UserDefined6 AS ReturnBooked
Note that the data type of UserDefined6 is nvarchar. :(
Thank you!
You need to change the GETDATE() in the snippet to your value, and it is not a good practice to keep date values in nvarchar, so you will need some conversion first.
something like that:
SELECT CONVERT(VARCHAR(8), DATEADD(DAY, 1, (CONVERT(DATETIME,UserDefined6))),112) AS ReturnBooked
FROM dbo.AdditionalDetailInfo
As datatype of your column is nvarchar, Dateadd function on nvarchar will fail, so First you need to convert the column value to datetime and then use the DateAdd function, like below
Select DATEADD(DAY, 1, CONVERT(Datetime,ReturnBooked))
After looking at the image of sample data, it seems you have a row with date text in wrong format 08/010/2018. The conversion will fail for this particular row, so recommended to fix such bad data.

Fetch Previous day record using sql server using Date field

I want to fetch previous day record from the table using a date field in Sql Server.
However I'm using the below sql statements but it's not giving any record.
TDTE = CAST(DATEADD(DD,-1,CURRNT_TIMESTAMP) AS DECIMAL(8,0))
OR
TDTE=CAST(DATEADD(DD,-1,GETDATE())AS DECIMAL(8,0))
where TDTE column is in YYYYMMDD format.
Remove the Cast function Dateadd returns Date not a Integer value. Try this.
Where TDTE = Cast(DATEADD(DD,-1,GETDATE()) as Date)
Try this.
Where TDTE = CONVERT(VARCHAR(10), DATEADD(DAY,-1,GETDATE()), 112)
OR(in decimal format)
Where TDTE = CAST(CONVERT(VARCHAR(10), DATEADD(DAY,-1,GETDATE()), 112)AS DECIMAL(18,0))

The conversion of a datetimeoffset data type to a datetime data type resulted in an out-of-range value

Using SQL Server 2008.I have a table called User which has a column LastLogindata with datetimeoffset datatype
The following query works on production server but not on replication server.
select top 10 CAST(LastLoginDate AS DATETIME) from User.
I am getting the following error.The conversion of a datetimeoffset data type to a datetime data type resulted in an out-of-range value.
Thanks
Check the LastLoginDate columns value like this '0001-01-01' or '0001/01/01'.
If u have means get this error ..
Try this one
select top 10 CAST(CASE when cast(LastLoginDate as varchar) = '0001-01-01 00:00:00'
THEN NULL ELSE GETDATE() end AS DATETIME) from User
If a field in database is of type datetimeoffset type, then it should contain date within range 0001-01-01 through 9999-12-31. I think the issue is the date inside your database.
Please check the official link of SQL server Click Here
I solved it this way. I had an nvarchar(max) column casted as an xml and used the T-SQL expression ISDATE() to exclude the bad rows in the where clause.
where cast(DataObject as xml).value('(/DataObjects/#LastLoginDate)[1]', 'varchar(10)') is not null
and isdate(cast(DataObject as xml).value('(/DataObjects/#LastLoginDate)[1]', 'varchar(10)')) = 1
On SQL Server 2016, I used:
CONVERT(DATETIME2, DateValueColumn)
This worked for values that were giving errors when trying to convert to DATETIME, giving the message "The conversion of a datetimeoffset data type to a datetime data type resulted in an out-of-range value." The offending values had dates of 0001-01-01, as a previous answer has mentioned.
Not sure if this works on SQL Server 2008 though.

Average a time value in SQL Sever 2005

I've got a varchar field in SQL Sever 2005 that's storing a time value in the format "hh:mm"ss.mmmm".
What I really want to do is take the average using the built in aggregate function of those time values. However, this:
SELECT AVG(TimeField) FROM TableWithTimeValues
doesn't work, since (of course) SQL won't average varchars. However, this
SELECT AVG(CAST(TimeField as datetime)) FROM TableWithTimeValues
also doesn't work. As near as I can tell, SQL doesn't know how to convert a value with only time and no date into a datetime field. I've tried a wide variety of things to get SQL to turn that field into a datetime, but so far, no luck.
Can anyone suggest a better way?
SQL Server can convert a time-only portion of a datetime value from string to datetime, however in your example, you have a precision of 4 decimal places. SQL Server 2005 only recognizes 3 places. Therefore, you will need to truncate the right-most character:
create table #TableWithTimeValues
(
TimeField varchar(13) not null
)
insert into #TableWithTimeValues
select '04:00:00.0000'
union all
select '05:00:00.0000'
union all
select '06:00:00.0000'
SELECT CAST(TimeField as datetime) FROM #TableWithTimeValues
--Msg 241, Level 16, State 1, Line 1
--Conversion failed when converting datetime from character string.
SELECT CAST(LEFT(TimeField, 12) as datetime) FROM #TableWithTimeValues
--Success!
This will convert valid values into a DATETIME starting on 1900-01-01. SQL Server calculates dates based on 1 day = 1 (integer). Portions of days are then portions of the value 1 (i.e. noon is 0.5). Because a date was not specified in the conversion, SQL Server assigned the value of 0 days (1900-01-01), which accommodates our need to average the time portion.
To perform an AVG operation on a DATETIME, you must first convert the DATETIME to a decimal value, perform the aggregation, then cast back. For example
SELECT CAST(AVG(CAST(CAST(LEFT(TimeField, 12) as datetime) AS FLOAT)) AS DATETIME) FROM #TableWithTimeValues
--1900-01-01 05:00:00.000
If you need to store this with an extra decimal place, you can convert the DATETIME to a VARCHAR with time portion only and pad the string back to 13 characters:
SELECT CONVERT(VARCHAR, CAST(AVG(CAST(CAST(LEFT(TimeField, 12) as datetime) AS FLOAT)) AS DATETIME), 114) + '0' FROM #TableWithTimeValues
Try this
AVG(CAST(CAST('1900-01-01 ' + TimeField AS DateTime) AS Float))
You really should store those in a datetime column anyway. Just use a consistent date for that part (1/1/1900 is very common). Then you can just call AVG() and not worry about it.
I used Cadaeic's response to get an answer I was looking for, so I thought I should share the code....
I was looking for a query that would average ALL my times together and give me an overall Turn Around Time for all approvals. Below is a nested statement that gives you the AVG TAT for individual id's and and when nested an overall TAT
SELECT
-- calculates overall TAT for ALL Approvals for specified period of time
-- depending on parameters of query
CONVERT(VARCHAR, CAST(AVG(CAST(CAST(LEFT(Tat_mins, 12) as datetime) AS FLOAT)) AS DATETIME), 108) + '0'
from
(
-- tat is for individual approvals
SELECT
dbo.credit_application.decision_status,
dbo.credit_application.application_id,
cast(dbo.credit_application.data_entry_complete as date) as'Data Entry Date',
cast(dbo.credit_application.decision_date as DATE) as 'Decision Date',
avg(datediff(minute, dbo.credit_application.data_entry_complete, dbo.credit_application.decision_date)) as 'TAT Minutes',
convert (char(5), DateAdd(minute, Datediff(minute,dbo.credit_application.data_entry_complete, dbo.credit_application.decision_date),'00:00:00'),108) as 'TAT_Mins'
FROM dbo.credit_application
where Decision_status not in ('P','N')
group by dbo.credit_application.decision_status,
dbo.credit_application.data_entry_complete,
dbo.credit_application.decision_date
--dbo.credit_application.application_id
)bb
How do you think to average on datetime?
I guess that you need to GROUP BY some period (Hour?), and display Count(*)?
SQL Server stores datetime data as 2 4-byte integers, hence a datetime take 8 bytes. The first is days since the base date and the second is milliseconds since midnight.
You can convert a datetime value to an integer and perform mathematical operations, but the convert only returns the "days" portion of the datetime value e.g. select convert(int,getdate()). It is more difficult to return the "time" portion as an integer.
Is using SQL Server 2008 an option for you? That version has a new dedicated time data type.
Thanks, Andy.
I'd work out the difference between all of the dates and an arbitrary point (01/01/1900), average it and then add it back on to the arbitrary point.

Resources