convert nvarchar to smalldatetime in sql server - sql-server

I have one table in which nvarchar data are there.
Table
18-FEB-11 10.29.52.000000000 AM
20-FEB-11 04.10.40.000000000 PM
23-SEP-10 10.34.57.714000000 AM
08-OCT-10 09.41.16.921000000 PM
I want to convert this field to small date time in sql server 2008 R2
How can i convert it.
Expected OUTPUT:
2011-02-18 10:29:52
2011-02-20 16:10:40
2010-09-23 10:34:57
2010-10-08 21:41:16

Try this please
declare #s_date as nvarchar(100)= '18-FEB-11 10.29.52.000000000 AM'
SELECT CONVERT(nvarchar(100),CAST(REPLACE(REPLACE(#s_date, SUBSTRING(#s_date, 19, 10),''),'.',':') as datetime), 120)
result : 2011-02-18 10:29:52

this should work too:
DECLARE #datestring NVARCHAR(50) = '08-OCT-10 09.41.16.921000000 PM'
SELECT CAST(REPLACE(LEFT(#datestring,18),'.',':') + RIGHT(#datestring,2) AS SMALLDATETIME)

Related

Convert NVARCHAR containg Timezone info to DATETIME in SQL Server

I have the following NVARCHAR field is SQL Server:
Sun Mar 26 23:47:06 GMT+03:00 2017
I wish to convert it to DATETIME in tSQL. How can I do that??? Using the CONVERT() and CAST() functions returns the following error
Conversion failed when converting date and/or time from character string.
I have tried converting to DATETIME, DATE, DATETIME2, DATETIMEOFFSET and none worked.
try this
Declare #dt varchar(50)
set #dt = 'Sun Mar 26 23:47:06 GMT+03:00 2017'
select CAST(left(stuff(stuff(#dt, 1, 4, ''), 8, 0, right(#dt, 4) + ' '), 20) as DATETIME)
Result
2017-03-26 23:47:06.000

Convert varchar to DateTime not working on table but works on individual values

I have a table with column ImportDate of datatype varchar(100).
I want to convert its values from varchar to Datetime and for that I have used this query:
select
convert(datetime, ImportDate)
from ImportHistory
But it throws an exception with message
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
But when I individually select each value and run the statement it works fine. For example the below query works perfectly, and so do all the values in the table
select convert(Datetime, '1826-07-04 18:20:00')
There are no null values in that table and below are the values:
1826-07-04 18:20:00
1826-07-04 18:20:00
1917-11-08 11:11:00
2003-07-16 16:02:00
1984-06-08 00:00:00
2004-06-05 00:00:00
1826-07-04 18:20:00
1826-07-04 18:20:00
1917-11-08 11:11:00
2003-07-16 16:02:00
1984-06-08 00:00:00
2004-06-05 00:00:00
If you're using SQL Server 2012+, use TRY_PARSE or TRY_CONVERT in this kind of scenario:
DECLARE #ImportHistory TABLE (ImportDate VARCHAR(100))
INSERT #ImportHistory
VALUES
('1826-07-04 18:20:00'),
('1826-07-04 18:20:00'),
('1917-11-08 11:11:00'),
('2003-07-16 16:02:00'),
('1984-06-08 00:00:00'),
('2004-06-05 00:00:00'),
('1826-07-04 18:20:00'),
('1826-07-04 18:20:00'),
('1917-11-08 11:11:00'),
('Invalid!'),
('2003-07-16 16:02:00'),
('1984-06-08 00:00:00'),
('2004-06-05 00:00:00')
SELECT
ImportDate, TRY_CONVERT(datetime, ImportDate) as dt
FROM #ImportHistory
WHERE TRY_CONVERT(datetime, ImportDate) IS NULL
-- output: Invalid!, NULL
To find the invalid value. If you want invalid values to be converted to NULL, you can remove the WHERE clause and just use TRY_PARSE in place of CONVERT.
The dates you've listed are all valid, but it's very likely in your actual table you have at least one invalid date - or at least not one that can be parsed as is (extra space, month/day stored in different culture format, etc.).
If you must keep your column as a VARCHAR for some unknown reason and you want to make sure that applications don't insert unparsable dates into it, you could add a constraint
ALTER TABLE ImportHistory
ADD CONSTRAINT CK_ImportDate
CHECK(TRY_CONVERT(datetime, ImportDate) IS NOT NULL)
If you don't have SQL Server 2012+, you could try making a cursor to find the invalid data:
DECLARE #dt VARCHAR(100);
DECLARE #dt2 DATETIME;
BEGIN TRY
DECLARE test_cursor1 CURSOR FOR
SELECT Importdate FROM #ImportHistory
OPEN test_cursor1
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM test_cursor1 INTO #dt
SET #dt2 = CONVERT(datetime, #dt)
END
END TRY
BEGIN CATCH
SELECT #dt
END CATCH
-- output: Invalid!
This resolved the issue.
Select Convert(Datetime, LTRIM ( RTRIM ( REPLACE ( REPLACE ( REPLACE ( ImportDate, CHAR(10), ''), CHAR(13), ''), CHAR(9), '') ) )) from ImportHistory
Thank you All !!

Convert date from dd-mm-yyyy to yyyy-mm-dd in SQL Server

I want to convert given date into the format YYYY-MM-DD.
Given date:
DECLARE #Date1 VARCHAR(50) = '30-01-2015'
Now I want to convert it into the 2015-01-30.
My try:
Try1:
SELECT CONVERT(VARCHAR(50),'30-01-2015',126)
Try2:
SELECT CONVERT(VARCHAR(50),'30-01-2015',120)
For both try the result remain same that is 30-01-2015.
Try this:
DECLARE #Date1 VARCHAR(50) = '30-01-2015'
SELECT CONVERT(VARCHAR(10), CONVERT(date, #Date1, 105), 23)
Try this way
SELECT CONVERT(date,'30-01-2015',103)
Convert date from dd-mm-yyyy hh:mm:ss to yyyy-mm-dd hh:mm:ss in SQL Server
convert(datetime,'18-11-2019 00:00:00',105) // will return 2019-11-18 00:00:00.000

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

I have below SQL.
UPDATE student_queues
SET Deleted=0,
last_accessed_by='raja',
last_accessed_on=CONVERT(VARCHAR(24),'23-07-2014 09:37:00',113)
WHERE std_id IN ('2144-384-11564')
AND reject_details='REJECT'
when I ran the above SQL the below exception has been throwed.
Conversion failed when converting date and/or time from character string.
If you're trying to insert in to last_accessed_on, which is a DateTime2, then your issue is with the fact that you are converting it to a varchar in a format that SQL doesn't understand.
If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:
UPDATE student_queues
SET Deleted=0,
last_accessed_by='raja',
last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
Or if you want to use CAST, replace with:
CAST('2014-07-23 09:37:00.000' AS datetime2)
This is using the SQL ISO Date Format.
Seems like last_accessed_on, is a date time, and you are converting '23-07-2014 09:37:00' to a varchar. This would not work, and give you conversion errors. Try
last_accessed_on= convert(datetime,'23-07-2014 09:37:00', 103)
I think you can avoid the cast though, and update with '23-07-2014 09:37:00'. It should work given that the format is correct.
Your query is not going to work because in last_accessed_on (which is DateTime2 type), you are trying to pass a Varchar value.
You query would be
UPDATE student_queues SET Deleted=0 , last_accessed_by='raja', last_accessed_on=convert(datetime,'23-07-2014 09:37:00', 103)
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
DECLARE #FromDate DATETIME
SET #FromDate = 'Jan 10 2016 12:00AM'
DECLARE #ToDate DATETIME
SET #ToDate = 'Jan 10 2017 12:00AM'
DECLARE #Dynamic_Qry nvarchar(Max) =''
SET #Dynamic_Qry='SELECT
(CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN
EMP_DOCUMENT.EXPIRY_DATE ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
)FROM CR.EMP_DOCUMENT as EMP_DOCUMENT WHERE 1=1
AND (
CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN EMP_DOCUMENT.EXPIRY_DATE
ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
) BETWEEN '''+ CONVERT(CHAR(10), #FromDate, 126) +''' AND '''+CONVERT(CHAR(10), #ToDate , 126
)
+'''
'
print #Dynamic_Qry
EXEC(#Dynamic_Qry)

time format in SQL Server

Does anyone know how can I format a select statement datetime value to only display time in SQL Server?
example:
Table cuatomer
id name datetime
1 Alvin 2010-10-15 15:12:54:00
2 Ken 2010-10-08 09:23:56:00
When I select the table I like the result will display as below
id name time
1 Alvin 3:12PM
2 Ken 9:23AM
Any way that I can do it in mssql?
You can use a combination of CONVERT, RIGHT and TRIM to get the desired result:
SELECT ltrim(right(convert(varchar(25), getdate(), 100), 7))
The 100 you see in the function specifies the date format mon dd yyyy hh:miAM (or PM), and from there we just grab the right characters.
You can see more about converting datetimes here.
You can use the CONVERT function like this:
SELECT CONVERT(varchar, your_datetime, 108)
However, this is 24-hour clock, no AM/PM.
This will get the time from a datetime value and also give the am or pm add on
SELECT RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),8)),7)
will always return the date in HH:mmAM format.
Note the lack of space
Or
SELECT REPLACE(REPLACE(RIGHT('0'+LTRIM(RIGHT(CONVERT(varchar,getDate(),100),7)),7),'AM',' AM'),'PM',' PM')
will always return the date in HH:mm AM format.
Hope that helps.
PK
Try:
select convert(varchar, getdate(), 108)
+ ' ' + RIGHT(convert(varchar, getdate(), 100), 2) as Time
You might be able to use:
select
convert(varchar,getdate(),114)
You might be able to manually construct the query like:
string query = string.Format("INSERT INTO test (DateOnlyField, TimeOnlyField) VALUES ('{0}', '1899-12-30 {1}')", DateTime.Today.ToShortDateString(), TimeString)
I dunno if this might work to:
Create Table Schedule( ScheduleID Integer Identity, ScheduledTime DateTime )
Go
Insert Into Schedule( ScheduledTime ) Values( '10:15:00 AM' )
Go
Select ScheduledTime As DBScheduledTime, Convert( VarChar( 10 ), ScheduledTime, 114 ) As ScheduledTime
From Schedule
Go
Drop Table Schedule
Go
If You are using SQL Server 2008 or Higher You can use the following statement:
SELECT Convert( VarChar( 10 ), CAST([columnName] AS TIME(0)), 100 )
If you are using MySql
you can use TIME_FORMAT()
Code ↓↓
SELECT name, time_format(datatime,'%H:%i') as tine from cuatomer

Resources