Convert String column to DataTime - sql-server

In my .net winform application i m importing excel data to SQL server. in my excel sheet i have 'STRT_TM' column containing dates in 03/01/2017 21:33:22 format. i want to do explicit conversion because in implicit conversion convert function is unable to determine whether the date is dd/mm/yyyy or mm/dd/yyyy.
In Sql Server i tried to convert a string to date. here is the code
select convert(smalldateTime,SUBSTRING('03/01/2017 14:05:34',7,4)+
SUBSTRING('03/01/2017 14:05:34',1,2) + SUBSTRING('03/01/2017 14:05:34',4,2))
the result is 2017-03-01 00:00:00
but when i try to include time part it gives error.
here is the code.
select convert(smalldateTime,SUBSTRING('03/01/2017 14:05:34',7,4)+
SUBSTRING('03/01/2017 14:05:34',1,2) + SUBSTRING('03/01/2017 14:05:34',4,2) +
Substring('03/01/2017 14:05:34',12,8))
and error is
Msg 295, Level 16, State 3, Line 3
Conversion failed when converting character string to smalldatetime data type.
any help will be appreciated.

You missed a space between date and time:
select convert(smalldateTime,
Substring('03/01/2017 14:05:34',7,4) +
Substring('03/01/2017 14:05:34',1,2) +
Substring('03/01/2017 14:05:34',4,2) + ' ' +
Substring('03/01/2017 14:05:34',12,8))

Related

SQL server error "Conversion failed when converting the varchar value 'False' to data type int"

Greetings im trying to join these 2 tables to find some data for a report im creating and im getting the error Conversion failed when converting the varchar value 'False' to data type int. Any idea why this is happening? I cant spot where i wrote wrong the code.!! any answer would be welcomed!!!
SELECT L.CUSTNO, CUST_NAME1, CUST_NAME2, CUST_NAME3
,CUST_NAME4, L.BRANCH, REFER_NO
,RIGHT('000000' + CONVERT(VARCHAR, L.CUSTNO), 6) + ' - '
+CAST(LOAN_PRODUCT AS CHAR(4)) + ' - '
+RIGHT('00' + CONVERT(VARCHAR, LOAN_ACC_SEQ_NO), 2) ACC_STR
,[CHECK_PRIN], [L_PRIN], [L_INT], [L_INTLQ], [L_EXP], [L_ACCR]
,[INV_BILL_CHARG_AMT], [P_PRIN], [P_INT], [P_OTH], [P_EXP]
,[P_PRV_S_INT], [P_ACCRUED], [P_OFF_ACCR]
FROM BleckBase1.dbo.[lm-loanacc] AS L
join BleckBase1.dbo.[lm-CUSTOMERMF] AS C ON L.CUSTNO = C.CUSTNO
WHERE ToClose = 0

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in TSQL

In my T-SQL select there appears to be an error with my datetime
select
t.F47, t.F53, t.F40, t.F162, t.F163,
N'10' as kostenart, t.F39, t.F2, t.F5,
convert(nvarchar, cast(t.F9 as datetime), 112),
t.PARID, 20170928135800 as exportzeitstempel
from
T_TRANS6 as t
where
t.F20 = N'Erledigt'
and t.F9 < convert(datetime, '01.09.2017 00:00:00', 104)
The error message is German and it says:
Meldung 242, Ebene 16, Status 3, Zeile 1
Bei der Konvertierung eines nvarchar-Datentyps in einen datetime-Datentyp liegt der Wert außerhalb des gültigen Bereichs.
I tried to translate this to:
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value."
I really don't know how I did from so thanks for any help guys
Your problem is triggered by cast(t.F9 as datetime).
Please do : SELECT getdate(); to get the implicit "datetime to string" convertion format.
WARNING : Implicit convertion format are set at the instance level. It can differ from a server to another, even in the same compagny...
This will gives you someting like dd.MM.yyyy HH:mm:ss or yyyy-MM-dd HH:mm:ss or ...
The given format is the one expected and required for all F9 of TRANS6 table records!!
A single TRANS6.F9 with a wrong formating patern will raise this ERROR. So analyse your F9 data, find the concerned rows, clean them and retry...
NOTE : CONVERT(NVARCHAR(8), getdate(),112) get a string like YYYYMMDD (Ex : '20170928') witch is the only sortable string format of dates...
EDIT : F9 = '2016.10.30' and Implicit convertion expect '2016-10-30' !!
Try this :
select
t.F47, t.F53, t.F40, t.F162, t.F163,
N'10' as kostenart, t.F39, t.F2, t.F5,
convert(nvarchar, convert(datetime,t.F9,102), 112),
t.PARID, 20170928135800 as exportzeitstempel
from
T_TRANS6 as t
where
t.F20 = N'Erledigt'
and t.F9 < convert(datetime, '01.09.2017 00:00:00', 104)
Does it works?

Query fails on "converting character string to smalldatetime data type"

I've been tasked with fixing some SQL code that doesn't work. The query reads from a view against a predicate. The query right now looks like so.
SELECT TOP (100) Beginn
FROM V_LLAMA_Seminare
//Removal of the following line makes the query successful, keeping it breaks it
where Beginn > (select cast (getdate() as smalldatetime))
order by Beginn desc
When I run the above query, I am greeted with the following error.
Msg 295, Level 16, State 3, Line 1
Conversion failed when converting character string to smalldatetime data type.
I decided to remove the WHERE clause, and now it runs returning 100 rows.
At first, I thought that behind the scenes, SQL Server was somehow including my predicate when bringing back the View . But then I investigated how the View was being created, especially the Beginn field, and at no point does it return a String.
Long story short, the column that becomes the Beginn field is a BIGINT timestamp like 201604201369.... The original user transforms this BIGINT to a smalldatetime using the following magic.
....
CASE WHEN ma.datum_dt = 0
THEN null
ELSE CONVERT(smalldatetime, SUBSTRING(CAST(ma.datum_dt AS varchar(max)),0,5) + '-' +
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),5,2) + '-' +
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),7,2) + ' ' +
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),9,2) +':'+
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),11,2) +':' +
RIGHT(CAST(ma.datum_dt AS varchar(max)),2)) END AS Beginn
...
My last attempt at finding the problem was to query the view and run the function ISDATE over the Beginn column and see if it returned a 0 which it never did.
So my question is two fold, "Why does a predicate break something" and two "Where on earth is this string error coming from when the Beginn value is being formed from a BIGINT".
Any help is greatly appreciated.
This problem is culture related...
Try this and then change the first SET LANGUAGE to GERMAN
SET LANGUAGE ENGLISH;
DECLARE #bi BIGINT=20160428001600;
SELECT CASE WHEN #bi = 0
THEN null
ELSE CONVERT(datetime, SUBSTRING(CAST(#bi AS varchar(max)),0,5) + '-' +
SUBSTRING(CAST(#bi AS varchar(max)),5,2) + '-' +
SUBSTRING(CAST(#bi AS varchar(max)),7,2) + ' ' +
SUBSTRING(CAST(#bi AS varchar(max)),9,2) +':'+
SUBSTRING(CAST(#bi AS varchar(max)),11,2) +':' +
RIGHT(CAST(#bi AS varchar(max)),2)) END AS Beginn
It is a very bad habit to think, that date values look the same everywhere (Oh no, my small application will never go international ...)
Try to stick to culture independent formats like ODBC or ISO
EDIT
A very easy solution for you actually was to replace the blank with a "T"
SUBSTRING(CAST(ma.datum_dt AS varchar(max)),7,2) + 'T' +
Then it's ISO 8601 and will convert...
The solution was found after looking through #Shnugo's comment. When I took my query which contained the Bigint->Datetime conversion logic, and put it into a CTE with "TOP 100000000" to avoid any implicit conversion actions, my query worked. Here is what my view looks like now with some unimportant parts omitted.
---Important part---
CREATE VIEW [dbo].[V_SomeView] AS
WITH CTE AS (
SELECT TOP 1000000000 ma.id AS MA_ID,
---Important part---
vko.extkey AS ID_VKO,
vko.text AS Verkaufsorganisation,
fi.f7000 AS MDM_Nr,
vf.f7105 AS SAPKdnr,
CASE WHEN ma.datum_dt = 0 --Conversion logic
CASE WHEN ma.endedatum_dt = 0 --Conversion logic
CONVERT(NVARCHAR(MAX),art.text) AS Art,
.....
FROM [ucrm].[dbo].[CRM_MA] ma,
[ucrm].[dbo].[CRM_fi] fi,
[ucrm].[dbo].[CRM_vf] vf,
[ucrm].[dbo].[CRM_ka] vko,
[ucrm].[dbo].[CRM_ka] art,
[ucrm].[dbo].[CRM_ka] kat
where ma.loskz = 0
and fi.loskz = 0
and vf.loskz = 0
and fi.F7029 = 0
and vf.F7023 = 0
...
GROUP BY ma.id,
vko.extkey,
vko.text,
fi.f7000 ,
vf.f7105,
ma.datum_dt,
ma.endedatum_dt,
....
)
select * FROM CTE;

convert string date to date type in sql server 2012

In a school website, I want to enable the admin to filter students based on date range when they were born. Dates in my tblStudent are stored as strings, so I cannot use:
SELECT ts.Name from tblStudent ts WHERE ts.BirthDay>'1367/01/31' AND ts.BirthDay<'1377/01/31'
I have saved dates (Jalali Format) in database table tblStudent. I need to do comparison based on dates. So I need to convert date strings to date type in sql server. To this purpose I used:
SELECT convert(date,tblStudent.BirthDay) from tblStudent
However,It stops after 27 results with the following error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
I have the following date strings in my tblStudent table.
1379/09/01
1375/04/20
1378/03/02
1378/03/21
1378/04/18
1378/04/18
1378/05/05
1375/04/20
1379/01/03
1378/03/01
1370/09/09
1378/03/22
1375/09/15
1379/09/01
1379/09/10
1375/04/08
1375/05/06
1370/09/09
1379/10/10
1375/04/10
1375/11/01
1375/04/04
1375/08/11
1375/05/05
1376/09/19
1375/12/12
1376/01/13
1375/15/10
1375/04/14
1375/04/04
1375/05/14
1374/11/11
1375/05/30
1375/05/14
1377/12/13
1377/02/31
1377/12/14
1377/01/13
1375/05/31
1377/11/05
1377/07/05
1375/05/31
1377/03/01
1377/04/01
1377/05/02
1377/05/04
1377/03/03
1377/01/14
1377/05/30
1377/04/31
1375/05/30
1376/06/12
1375/12/10
1377/08/14
1377/03/04
1375/04/08
1375/07/18
1375/08/09
1375/09/12
1375/11/12
1376/12/12
1375/01/02
1375/05/09
1375/04/09
1376/01/01
1375/01/30
1377/04/04
1375/05/23
1375/05/01
1377/02/01
1367/12/05
1375/05/31
1373/03/29
1373/03/03
1375/05/05
Is there a way to convert these string dates to date type and then compare them with some query? For example, such a query can be:
SELECT ts.Name from tblStudent ts where ts.BirthDay>'1375/05/31'
I think you can make them ints and compare them:
SELECT ts.Name
FROM tblStudent ts
WHERE CONVERT(INT,REPLACE(ts.BirthDay,'/','') > 13670131
AND CONVERT(INT,REPLACE(ts.BirthDay,'/','') < 13770131
Or for your second example:
SELECT ts.Name
FROM tblStudent ts
WHERE CONVERT(INT,REPLACE(ts.BirthDay,'/','') > 13750531
This would work because having the order Year-Month-Day will ensure that the int representation of a later time will be greater than the int representation of an earlier time.
I really do not know if this is the best idea, but it is an idea of how to do it. After all you would be using a conversion.
From C# you have a few options:
If your input is string:
var dateInt = Int32.Parse(dateString.Replace("/",""));
If your input is Date then:
var dateInt = Int32.Parse(dateValue.ToString("yyyyMMdd"));
You could also pass the string itself in the db and let the db do the work for you :
DECLARE #Date AS VARCHAR(10)
SET #Date = ...--This will be filled with the inputed string
DECLARE #DateINT AS INT
SET #DateINT = CONVERT(INT,REPLACE(#Date,"/",""))

Entity Framework stored procedure error with DateTime

Hi
I am getting an error
'Conversion failed when converting date and/or time from character string'
When calling a stored procedure using EF4.
I am passing from my c# 2 DateTimes like this
#FromDate='2010-11-10 12:30:14.2558729'
#ToDate= '2010-11-10 12:30:15.1169590'
How can I prevent this error?
if I do the following in my UI it works
FromDate = new DateTime (SelectedFromDate.Year,SelectedFromDate.Month,SelectedFromDate.Day),
ToDate = new DateTime(SelectedToDate.Year, SelectedToDate.Month, SelectedToDate.Day),
Thanks for any suggestions
Reduce the number of digits on the fractional seconds to three. Try it out...
What you are trying to do:
select convert(datetime,'2010-11-10 12:30:14.2558729')
-- ^^^^^^^
OUTPUT:
-----------------------
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting datetime from character string.
Using only 3 decimal digits:
select convert(datetime,'2010-11-10 12:30:14.255')
-- ^^^
OUTPUT:
-----------------------
2010-11-10 12:30:14.257
(1 row(s) affected)

Resources