Cast string as datetime issue
I have installed SQL Server Express 2008 R2 on a Windows 7, language Brazilian-Portuguese ( PT-BR ). When I run a function which converts string to datetime it is raising conversion exception. I have tried the ANSI format 'yyyy-mm-dd' and 'mm-dd-yyyy', but
the only one that works is 'dd-mm-yyyy'. Is there any kind of settup that should be made to reset SQL Server to the ANSI default ?
Jayme Jeffman
Datetime/string conversion:
http://www.sqlusa.com/bestpractices/datetimeconversion/
Starting with SQL Server 2012, TRY_CONVERT() is available for date validity check:
http://beyondrelational.com/modules/2/blogs/70/posts/19841/data-validation-using-tryconvert-function.aspx
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014
Similar Messages
-
Issue converting String to DateTime to subtract 1 Day duration in XSLT
Hi
I need to subtract 1 Day duration from the input date which is in format "yyyy-mm-ddT00:00:00"( data type=String)
I tried using the available function: subtract-dayTimeDuration-from-dateTime() But, this function expects input as datatype datetime and hence on using this I am getting Null as the result of the transformation.
I have used dateTime() to convert the input string but it doesnt seem to be working as i get error "Invalid Xpath expression(null).
Please help in identifying anyother way i can convert the String into dateTime format and hence subtract the duration. Or some other way of subtracting the duration of 1 day from string itself.
Thanks for the help!Hi,
It should work with the date on the format you have... Review the code, it may have some mistype... Also, in BPEL you should use the xp20 functions...
Have a look at this...
https://blogs.oracle.com/reynolds/entry/whats_the_time_mr_bpel
Hope this helps...
Cheers,
Vlad -
How to split the string by datetime in sql
Hi,
How to split the string by datetime in sql, I've a table with comments column stores comments by datetime, while selecting I want to split and show as in rows by each jobref.
can anyone help me in this please.
Thanks,declare @callcentre table (comments varchar(max),lbiref varchar(200))
insert into @callcentre
select '(28/10/2014 14:56:14) xyz ..... call logged (28/10/2014 14:56:58) xyz ..... call updated (28/10/2014 14:57:41)xyz ..... call updated','Vi2910201'
insert into @callcentre
select '(29/10/2014 14:56:14) xyz ..... call logged (29/10/2014 14:56:58) xyz ..... call updated (29/10/2014 14:57:41)xyz ..... call updated','Vi2910202'
insert into @callcentre
select '(30/10/2014 14:56:14) xyz ..... call logged (30/10/2014 14:56:58) xyz ..... call updated
output:
1) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call logged ,'Vi2910201'
2) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910201'
3) 28/10/2014 14:57:41, (28/10/2014 14:57:41)xyz ..... call updated,'Vi2910201'
4) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call logged ,'Vi2910202'
5) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910202'
6) 28/10/2014 14:57:41, (28/10/2014 14:57:41)xyz ..... call updated,'Vi2910202'
7) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call logged ,'Vi2910203'
8) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910203'
Thanks,
See this illustration
declare @callcentre table (comments varchar(max),lbiref varchar(200))
insert into @callcentre
select '(28/10/2014 14:56:14) xyz ..... call logged (28/10/2014 14:56:58) xyz ..... call updated (28/10/2014 14:57:41)xyz ..... call updated','Vi2910201'
insert into @callcentre
select '(29/10/2014 14:56:14) xyz ..... call logged (29/10/2014 14:56:58) xyz ..... call updated (29/10/2014 14:57:41)xyz ..... call updated','Vi2910202'
insert into @callcentre
select '(30/10/2014 14:56:14) xyz ..... call logged (30/10/2014 14:56:58) xyz ..... call updated','Vi2910203'
SELECT LEFT(p.u.value('.[1]','varchar(max)'),CHARINDEX(')',p.u.value('.[1]','varchar(max)'))-1) AS [Date],
'(' + p.u.value('.[1]','varchar(max)') AS comments,
lbiref
FROM
SELECT lbiref,CAST('<Root>' + STUFF(REPLACE(comments,'(','</Data><Data>'),1,7,'') + '</Data></Root>' AS XML) AS x
FROM @callcentre c
)t
CROSS APPLY x.nodes('/Root/Data')p(u)
and the output
Date comments lbiref
28/10/2014 14:56:14 (28/10/2014 14:56:14) xyz ..... call logged Vi2910201
28/10/2014 14:56:58 (28/10/2014 14:56:58) xyz ..... call updated Vi2910201
28/10/2014 14:57:41 (28/10/2014 14:57:41)xyz ..... call updated Vi2910201
29/10/2014 14:56:14 (29/10/2014 14:56:14) xyz ..... call logged Vi2910202
29/10/2014 14:56:58 (29/10/2014 14:56:58) xyz ..... call updated Vi2910202
29/10/2014 14:57:41 (29/10/2014 14:57:41)xyz ..... call updated Vi2910202
30/10/2014 14:56:14 (30/10/2014 14:56:14) xyz ..... call logged Vi2910203
30/10/2014 14:56:58 (30/10/2014 14:56:58) xyz ..... call updated Vi2910203
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page -
How do you cast 0 as DateTime? Is this possible to do...
I am using UNION to combine two tables. I get an error when doing so...
Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with date
SELECT TOP (100) PERCENT
Opportunity_Name
,Status
,Closed_Status
,Sales_Stage
,Expected_Close_Date
,Closed_Flag
,Total_Revenue
FROM
v_rpt_Opportunity
WHERE
(Expected_Close_Date >= DATEADD(MM, DATEDIFF(MM, 0, GETDATE()), 0))
UNION
SELECT TOP (100) PERCENT
0 AS Opportunity_Name
,0 AS Status
,0 AS Closed_Status
,Description AS 'Sales_Stage'
,0 AS Expected_Close_Date
,0 AS Closed_Flag
,0 AS Total_Revenue
FROM SO_Pipeline
WHERE Description NOT LIKE '%delete%'
I understand what is causing the error. In the top select statement both Closed_Status AND Expected_Close_Date are datetime values. But in the bottom statement they are int.
I understand what is causing the error. In the top select statement both Closed_Status AND Expected_Close_Date are datetime values. In the bottom statement they are int. So
I tried CASTing them as datetime, that didn’t work and I get this error.<o:p></o:p>
Conversion
failed when converting the varchar value 'Open' to data type int.
Is there a way to CAST 0 as a DateTime
Thank you,
SteveI think the issue is not with the dates, instead it's with either Status / Closed Status i.e. one of their value is “open” and error is when that value to “int” which is not possible. Try
casting them to varchars.
SELECT TOP (100) PERCENT
Opportunity_Name
,Status
,Closed_Status
,Sales_Stage
,Expected_Close_Date
,Closed_Flag
,Total_Revenue
FROM
v_rpt_Opportunity
WHERE
(Expected_Close_Date >= DATEADD(MM, DATEDIFF(MM, 0, GETDATE()), 0))
UNION
SELECT TOP (100) PERCENT
0 AS Opportunity_Name
,CAST(0 AS VARCHAR(10)) AS Status
,CAST(0 AS VARCHAR(10)) AS Closed_Status
,Description AS 'Sales_Stage'
,0 AS Expected_Close_Date
,0 AS Closed_Flag
,0 AS Total_Revenue
FROM SO_Pipeline
WHERE Description NOT LIKE '%delete%'
Narsimha -
Converting string to Datetime?
Hello all,
I have seen tons of titles in this forum with the same like mine, but none of them helped solve my issue. It seems very simple, but it gives me a format exception. I am just trying to convert a string to datetime with a specified format.
string convertToString;
convertToString = (theWeek.AddDays(i).ToString("dd/MM/yyyy"));
theDay = DateTime.ParseExact(convertToString, "dd'/'MM'/'yy", null),
Here theDay is also a DateTime variable.
These are the errors i get when I execute the code
1. When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
2. When going into the details of the exception this is what I see " String was not recognized as a valid DateTime".
Please advise!
Thanks all.
Thanks, SumeshThanks Ante & JayChase for the speedy response.
I did it the way you mentioned and i was able to get rid of the exception, but still it doesn't show up in the specified format. It shows the time too which I am not asking for.
this is what I get now "3/17/2015 12:00:00 AM" .
I just want 17/03/2015.
Thanks again.
Thanks, Sumesh
I think I see the "problem" here. I suspect that there isn't one.
string convertToString;
convertToString = (DateTime.Now.AddDays(5).ToString("dd/MM/yyyy"));
DateTime day = DateTime.ParseExact(convertToString, "dd/MM/yyyy", null);
This works perfectly, as it should. You appear to have set a breakpoint someplace and you're examining the Visual Studio "value" of the variable 'day.' You're unhappy that it displays in a manner that you don't like.
I believe that you're simply not understanding the difference between a System.DateTime object and a System.DateTime represented as a string.
To start with, a System.DateTime is a 64-bit integer value. According to the MSDN documentation page:
Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the
GregorianCalendar calendar (excluding ticks that would be added by leap seconds). For example, a ticks value of 31241376000000000L
represents the date, Friday, January 01, 0100 12:00:00 midnight. A DateTime value is always expressed in the context of an explicit or default calendar.
When you call the DateTime.ToString() method and specify an output style, you get the 64-bit value in the human-readable string representation you want. When you set a breakpoint and examine the variable in Visual Studio, you get the 64-bit value in
the human-readable string representation Visual Studio provides by default.
I hope this helps.
Content Removed -
Converting String to datetime format
I have a String which is in 04-DEC-78 format, I want it to be inserted in to a field in sql database.If I map directly I am getting
"Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The input data for the field/parameter "e_date" is invalid according to the expected SqlDbType DateTime. ---> System.FormatException: The string '04-DEC-65' is not a valid
AllXsd value.
Tried to convert the string to datetime format in Mapping but getting error
public DateTime FormatCheck(string param1)
IFormatProvider culture = new CultureInfo("en-US", true);
return DateTime.ParseExact(param1, "dd/MM/yyyy HH:mm:ss.fff", culture);
Inline Script Error: The type or namespace name 'CultureInfo' could not be found (are you missing a using directive or an assembly reference?)
Help me out!!HOLD ON!
Let's try to clear this up. If the input data is "04-DEC-78" then, sorry, none of the code posted so far will work.
"04-DEC-78" is not directly parsable so the .ParseExact format must match the source.
The format for xs:datetime is ISO 8601 which is like yyyy-MM-ddTHH:mm:ss-[offset]. Internally the sqlBinding will cast the XsdDateTime (the .Net xs:datetime implementation) to a SqlDateTime.
One very, very important missing detail is the type of the SQL parameter. Is it (SQL) datetime or string?
If the SQL parameter is datetime, then you can use this:
public string FormatCheck(string param1)
return DateTime.ParseExact(param1, "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture).ToString("s"); -
Hi,
I'm really struggling in converting a string which contains a dates to a DateTime datatype.
below is an example of how it looks
AdmissionDate
29.09.14 08:52
29.09.14 08:50
29.09.14 08:06Hi Sam,
you can use convert function to change the above string to datetime data type.
select
convert(datetime,'29.09.14 08:52',3)
select
convert(datetime,'29.09.14 08:50',3)
select
convert(datetime,'29.09.14 08:06',3)
Thanks, RajaSekhara Reddy . K -
I am trying to compare a DB2 date format to a date variable from SSIS. I have tried to set the variable as datetime and string. I have also casted the SQL date as date in the data flow task. I have tried a number of combinations of date formats, but no luck
yet. Does anyone have any insights on how to set a date (without the time) variable and be able to use it in the data flow task SQL? It has to be an easy way to accomplish that. I get the following error below:
An invalid datetime format was detected; that is, an invalid string representation or value was specified. SQLSTATE=22007".
Thanks!Hi Marcel,
Based on my research, in DB2, we use the following function to convert a string value to a date value:
Date(To_Date(‘String’, ‘DD/MM/YYYY’))
So, you can set the variable type to String in the package, and try the following query:
ACCOUNT_DATE BETWEEN '11/30/2013' AND Date(To_Date(?, ‘DD/MM/YYYY’))
References:
http://stackoverflow.com/questions/4852139/converting-a-string-to-a-date-in-db2
http://www.dbforums.com/db2/1678158-how-convert-string-time.html
Regards,
Mike Yin
TechNet Community Support -
Datetime issue SQL Server 2008R2
My server has
System Locale en-gb; English (United Kingdom)
Input Locale en-gb; English (United Kingdom)
SQL account @@language is British
I can insert the value '2013-01-18 16:05:21.683' into a DATETIME2 field but when trying to insert the same value into a DATETIME field I get the following error
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.
I can insert the value '2013-01-18T16:05:21.683' into the datetime field OK.
Why does it allow the insert into datetime2 but not datetime?
ThanksThanks everyone for looking at this. I know how I can get around the issue
I just wanted to know why entering the same value string into a datetime2 field works but doesn't into a datetime?
Both statements will be using the same language and dateformat settings. I would expect both to work or both to fail, not one works and one doesn't.
Works
declare @datetime2 datetime2
set @datetime2 = '2013-01-18 16:05:21.683'
select @datetime2
Fails
declare @datetime datetime
set @datetime = '2013-01-18 16:05:21.683'
select @datetime
Ok to explain that please see below explanation from books online
datetime
ANSI and ISO 8601 Compliance
datetime is not ANSI or ISO 8601 compliant.
from
http://msdn.microsoft.com/en-us/library/ms187819.aspx
datetime2 (from
http://msdn.microsoft.com/en-us/library/bb677335.aspx)
ANSI and ISO 8601 Compliance
The ANSI and ISO 8601 compliance of
date and time apply to
datetime2.
and this is what date and time says for ANSI compliance
date (http://msdn.microsoft.com/en-us/library/bb630352.aspx)
ANSI and ISO 8601 Compliance
date complies with the ANSI SQL standard definition for the Gregorian calendar: "NOTE 85 - Datetime data types will allow dates in the Gregorian format to be stored in the date range 0001–01–01 CE through 9999–12–31 CE."
The default string literal format, which is used for down-level clients, complies with the SQL standard form which is defined as YYYY-MM-DD. This format is the same as the ISO 8601 definition for DATE
time (http://msdn.microsoft.com/en-us/library/bb677243.aspx)
Using hour 24 to represent midnight and leap second over 59 as defined by ISO 8601 (5.3.2 and 5.3) are not supported to be backward compatible and consistent with the existing date and time types.
The default string literal format (used for down-level client) will align with the SQL standard form, which is defined as hh:mm:ss[.nnnnnnn]. This format resembles the ISO 8601 definition for TIME excluding fractional seconds.
So as such it turns out that datetime2 merges ANSI format for date and time which is YYYY-MM-DD hh:mm:ss whereas datetime is not ANSI complaint and will only accept date values in string literal formats as per below
ISO 8601
YYYY-MM-DDThh:mm:ss[.mmm]
YYYYMMDD[ hh:mm:ss[.mmm]]
ie either with T as time part separator or without - characters in the date part
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Convert string to datetime and then use in a where clause
I am trying to pull in warranty expiry dates that have been entered as strings and then perform a calculation as to which ones are expired, about to expire within
90 days or will expire in more than 90 days. I have got the query to a point where I have converted it to a datetime field (though I'm sure I used the right value to just give me the date, its giving me date and time) and have it printing out the machine name
and the warranty for that machine.
SELECT
machNameTab.machName
,convert(date,auditRsltManualFieldValues.fieldValue,103) AS warranty
FROM
machNameTab
INNER JOIN auditRsltManualFieldValues
ON machNameTab.agentGuid = auditRsltManualFieldValues.agentGuid
WHERE
machNameTab.groupName = N'root.company'
AND auditRsltManualFieldValues.fieldNameFK = 958472722796011
What I need to do next is change this so instead of just spitting out all the dates as 'Warranty', I want it to give me the fields 'Expired', 'Expiring' (expiry date is within 90 days of the current date) and 90Days (expiry date is over 90 days from the current
date)SELECT
machNameTab.machName
,convert(date,auditRsltManualFieldValues.fieldValue,103) AS warranty,
select
case
when datediff(day,getdate(),convert(date,auditRsltManualFieldValues.fieldValue,103) )<90 then 'Expiring'
when datediff(day,getdate(),convert(date,auditRsltManualFieldValues.fieldValue,103) )<0 then 'Expired'
when datediff(day,getdate(),convert(date,auditRsltManualFieldValues.fieldValue,103) )>=90 then '90Days'
end as status
FROM
machNameTab
INNER JOIN auditRsltManualFieldValues
ON machNameTab.agentGuid = auditRsltManualFieldValues.agentGuid
WHERE
machNameTab.groupName = N'root.company'
AND auditRsltManualFieldValues.fieldNameFK = 958472722796011
I added a case to your select. The case will output the strings you wanted based on the date. -
Convert/Cast string data type from file to DT_GUID into table
Hi to all
is there anyone who help me please?!?
I'm not able to resolve the following problem.
I have a .csv file with a string field A and its values are GUID.
I must export this .csv file into SQL Server Table which have a uniqueidentifier (GUID) field B.
I must map string field A to GUID field B of table.
But I get an error like this: "Error at Data Flow Task [Derived Column [xxx]]: Error code 0x800401F3 occurred attempting to convert from data type DT_WSTR to data type DT_GUID.".
I read other posts like this in this forum and i also tried the solution suggested in those posts.
The proposed solution had suggested of insert in the expression field of "Derived Column" Transformation this expression (DT_GUID) ("{" + [YourGuid] + "}") in place of (DT_GUID) [YourGuid].
But i get always the same error.
is there anyone who help me please to resolve this issue?!?The derived column expression should work if the yourGuid column contains a real guid.
Does the source looks something like: 25892e17-80f6-415f-9c65-7395632f0223
And are all rows filled with a correct value or are there also empty strings or null values?
Please mark the post as answered if it answers your question | My SSIS Blog:
http://microsoft-ssis.blogspot.com |
Twitter -
I need convert the date of string format 'MM/dd/yyyy' to datetime format 'MM/dd/yyyy' when the system date format is 'dd/MM/yyyy'.Since
I need to search values based on date where my database datetime is 'MM/dd/yyyy' format.In my opinion you should re-consider the assumption that the date picker returns a string. Maybe it is able to return a
DateTime object directly instead of string. Then you will pass this value as a parameter of SQL query. This should work regardless of computer configuration.
Otherwise, follow the previous string-based approaches. -
Convert string to datetime produces error
Hi All,
I am trying to convert a string to a datetime. When I use the formula below with an alias table, it gives me an error "Invalid Column Name c1.Date"
SELECT CONVERT(datetime,left([c1.Date],2)'/'substring([c1.Date],3,2)'/'right([c1.Date],4),101) AS Date
FROM callrecords c1
Is there another way to convert the string to a datetime?
I am using CR 2008 SP1.
Thank you in advance.What happen if you run the sql without the conversion,
SELECT c1.Date FROM callrecords c1
do you still get the same error message?
if you don't get the error message you can let crystal do the conversion for you by using the following function in a formula
CDate ({c1.Date}) -
Cast string to single precision
Hi,
I try to write a communication between a PC and a DSP which is
programmed to
understand some kind of ModBus. I tried to use MBmaster.vi, a freeware
of AIRtech in the netherlands.
I was successfull to 90% after a very short time - I get back a string
from the DSP which makes sense.
The only problem is to *convert* the 4Byte=8Hex=32Bits(=IEEE754 single
precision format) into the LabView single precision number it does
represent .
In other programming languages like C I think I could do this easily
on a very low level procedure or with one of these dangerous casts.
As a newbie to LabView I could not found neither one VI to do this or
find out which simple combination of VIs could solve the problems.
Are there any cracks
here who know *the* easy solution??
Thanx & Regards
Urs Bögli"Doug (CapeFl)" wrote in message news:<[email protected]>...
> Did you check the VI functions under Functions>String>Additional
> String to Number Functions?
> There are quite a few for converting to/from Hex, etc. I've used them
> for concatenating 4-bit strings into an 8-bit string (to get an 8-bit
> byte/word), also converting to/from Hex using some of the VIs I
> mentioned.
> Good Luck, Doug
Dough,
as a programmer for twenty years I have some problems to understand the way
labview does work with types and casts - other languages are much clearer about it
- or have I not found the ultimative help area yet ???
May I ask you to send me the VI off list?
thanks
Urs -
Fixed Query update DATETIME issue
I'm trying to convert a VARCHAR value to a DATETIME value in a table in a SQL database with the following Fixed Query Details:
update SAPQNJDB.MPM_AFKOL
set GSUZS = CONVERT(Datetime,'2012-03-28 11:10:00.000')
where AUFNR = '000001000648'
But I receive the error as below:
SQL error has occurred on query The SQL statement "update SAPQNJDB.MPM_AFKOL
set GSUZS = CONVERT(Datetime,'2012-03-28 11:10:00.000')
where AUFNR = '000001000648'" contains the syntax error[s]: - 2:14 - Intermediate-SQL syntax error: CONVERT or TRANSLATE function not allowed
- 2:30 - SQL syntax error: the token "," was not expected here
- 2:30 - expecting "using", found ','
SQL Version is 2008
SAP MII Version 15.0 sp 0 patch 0
Type: Querytemplate
Datasource Modes: Command
A normal select query on the same tables just works fine.Issue is solved.
Changing the datasource from DataSource(SQL) to IDBC(SQL) did the trick
Maybe you are looking for
-
Default value of quality inspection
Hi all when you enter a goods receipt against a purchase order. and a Quality Inspection is suggested as the stock type. Where does this default value come from? Thanks
-
My iPhone 5 will not open iTunes since yesterday after iOS 7 was installed. have tried different things to no avail. Help
-
To stop scroll bars appearing around iView
Hello all, I've placed a small iVIew in the tool area of the framework page, below the masthead, above the TLN; right beside the KM search iView. The user has noticed that when he doesn't have IE fully maximized, if he makes the window small enough t
-
Hi all, i'm going to upgrade a pair of WLC with a very old software image. Since this situation requires several intermediate upgrades, I was wondering if I can disable the distribution ports at the begining of the upgrade and then enable them at the
-
[Solved] How to see the VSFTPD's logs
I need to see the connections log: When a user logs in or logs out, its IP address, etc. Using journalctl -u vsftpd The only thing can see are the connection fails. Any idea about how to see the connection logs? uname -a Linux darkBit 3.19.2-1-ARCH