Convert String to Date in T-SQL - sql-server

I try to convert a string into a date in t-sql. However get results that I can't explain.
DECLARE #String as char(11)
DECLARE #TString as char(11)
SELECT #String = SUBSTRING([Flat File Source Error Output Column],1,CHARINDEX(',',[Flat File Source Error Output Column])-6)
FROM [ERROR].[Import_V2X]
SELECT #TString = '12/18/2009'
-- Check content before conversion
SELECT #TString as 'CheckTString'
SELECT #String as 'CheckString'
-- Convert the strings to date
SELECT CONVERT(date,#TString,101) as 'ConvertSuccess'
SELECT CONVERT(date,#String,101) as 'ConvertFails'
[Flat File Source Error Output Column] is defined as text in the table
This gives me the following result:
CheckTString
------------
12/18/2009
(1 row(s) affected)
CheckString
-----------
12/18/2009
(1 row(s) affected)
ConvertSuccess
--------------
2009-12-18
(1 row(s) affected)
ConvertFails
------------
Msg 241, Level 16, State 1, Line 16
Conversion failed when converting date and/or time from character string.
Anybody can explain me where the problem is or comes from ?
For me the strings look exactly the same :(

By the look of your output you have a line feed in the checkstring variable. If this is not just a copy and paste error in the question, that will cause the error that you are describing. See below
DECLARE #TString as char(11)
SELECT #TString = '
12/18/2009'
-- Check content before conversion
SELECT #TString as 'CheckTString'
-- Convert the strings to date
SELECT CONVERT(date,#TString,101) as 'ConvertFails'
Gives the following results.
(1 row(s) affected)
Msg 241, Level 16, State 1, Line 13
Conversion failed when converting date and/or time from character string.

If I had to guess it's because you're imported string has a non-visible character at the end of the string that doesn't allow it to convert. Your variable is char(11) but the string '12/18/2009' is only 10 characters long so that leaves room for 1 more character at the end.

Looks like #CheckString potentially has a newline character at the beginning.

Related

Convert string to datetime - SQL

I have a string parsed from XML which represents datetime.
String format is: '20200915114000' - (YYYYMMDDhhmmss)
Is there a function in SQL Server to convert or parse this string to datetime or should I split string manually and concatenate it into datetime?
How to do this, in 3 steps:
C:\> SQLCMD
1> select convert(datetime,'20200915114000' )
2> go
Msg 241, Level 16, State 1, Server ZES, Line 1
Conversion failed when converting date and/or time from character string.
1> select convert(datetime,'20200915 114000' )
2> go
Msg 242, Level 16, State 3, Server ZES, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
1> select convert(datetime,'20200915 11:40:00' )
2> go
-----------------------
2020-09-15 11:40:00.000
(1 rows affected)
1>
Conclusion you need to add a space and 3 ':' in the string to convert '20200915114000' to '20200915 11:40:00'. After this a simple CONVERT will do the trick.
Solution to my problem:
declare #sDate char(14), #sDateOK char(20)
set #sDate = '20200915114000'
set #sDateOK = substring(#sDate,1,8) + ' ' + substring(#sDate,9,2) + ':' + substring(#sDate,11,2) + ':' + substring(#sDate,13,2)
select convert(datetime,#sDateOK ) as Date

Error in if not exists query in SQL Server

What is wrong with this following query? I can't find the error. Can anyone help
me with this issue?
IF (NOT EXISTS(SELECT *
FROM chennai_metro_data
WHERE TIME1 ='09:00' AND DATE1 ='1-23-2017'))
BEGIN
INSERT INTO chennai_metro_data
VALUES (2021700002,'1-23-2017','09:00',1,0,555555)
END
ELSE
BEGIN
UPDATE chennai_metro_data
SET CUMFLOW = 555555
WHERE TIME1 = '09:00' AND DATE1 = '1-23-2017'
END
I'm getting this error:
Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with date
As a best practice, you should always define the list of columns you're inserting into when using INSERT - that helps avoid a lot of problems !
And also: for the dates, to be independent of any language & regional settings, try to use the ISO-8601 format - YYYYMDDD for just dates (no time), or YYYY-MM-DDTHH:MM:SS for date & time.
So try this code:
INSERT INTO chennai_metro_data(col1, col2, ...., colN)
VALUES (2021700002, '20170123', '09:00', 1, 0, 555555)
and replace col1 thorugh colN with your actual column names from that table that you want to insert data into.

Stored procedure conversion failed

I am creating a stored procedure where I have 3 "dynamic" parameters, first is an int and the second and third are datetime.
How the output looks like:
17 | 2016-01-24 11:28:22.233 | 2016-05-22 09:07:04.220
Due to my final application that is connecting to this stored procedure, I have to treat the date time values as nvarchar to be able to use the LIKE operator, so that the user can easily filter the throw those date time's
What I have done is to create query that works fine gets back the wanted output
SELECT *
FROM WATCHDOG.WatchdogUsr.WebsiteFailureLog
WHERE websiteID = 17
AND (((CONVERT(NVARCHAR(45), FailureLogStart, 121) LIKE '%2016-01%')))
But my stored procedure has an issue:
Msg 241, Level 16, State 1, Procedure WatchDogDataCollector, Line 5
Conversion failed when converting date and/or time from character string.
This is my stored procedure:
ALTER PROCEDURE [dbo].[WatchDogDataCollector]
#websiteID int = NULL,
#FailureLogStart NVARCHAR = NULL
AS
SELECT *
FROM WATCHDOG.WatchdogUsr.WebsiteFailureLog
WHERE websiteID = ISNULL(#websiteID,websiteID)
AND (((CONVERT(NVARCHAR(45), FailureLogStart, 121) LIKE '%'+#FailureLogStart+'%')))
Table schema:
Well, if you can't figure out what date part(s) the user enters, your only option is indeed to cast the datetime value to a string:
ALTER PROCEDURE [dbo].[WatchDogDataCollector]
#websiteID int = NULL,
#FailureLogStart VARCHAR(23) = NULL
AS
SELECT *
FROM WATCHDOG.WatchdogUsr.WebsiteFailureLog
WHERE websiteID = ISNULL(#websiteID,websiteID)
AND (((CONVERT(CHAR(23), FailureLogStart, 121) LIKE '%'+#FailureLogStart+'%')))
Note: the number of chars in a string representing datetime with style 121 is 23. there is no point in casting to nvarchar(45).

SQL Insert Datetime temp table truncated error

I'm trying to execute this code:
DECLARE #temp TABLE (Start dateTime, Name nvarchar)
INSERT INTO #temp (Start, Name)
VALUES (GETDATE(), 'Callum')
SELECT * FROM #temp
and I get this error:
Msg 8152, Level 16, State 4, Line 3 String or binary data would be
truncated. The statement has been terminated.
(0 row(s) affected)
I found out that I'm trying to fit too much data in the column, but I'm not sure how....
You need to specify the size in nvarchar. For Eg nvarchar(50)

How rigid is the max size of a VARCHAR in SQL Server?

i.e. if I create a VARCHAR(50) field, what happens if I try to assign it a value that's 100 characters long?
Will SQL Server let me do this? Is it somehow less efficient?
If you try forcing a large string into a smaller-size variable, the incoming string will be simply chopped off at the appropriate size.
declare #Variable varchar (50)
set #Variable = replace (SPACE (100), ' ' , '.')
print #Variable
the output is 50 characters long
..................................................
If you try to force a large string into a small sized Field in a Table, an Error will be raised
declare #MyTable Table
(
TestVariable varchar (50)
)
insert into #MyTable (TestVariable) select replace (SPACE (100), ' ' , '.')
select * from #MyTable
the output is
Msg 8152, Level 16, State 14, Line 6
String or binary data would be truncated.
The statement has been terminated.
TestVariable
------------------------------------------------
It will throw an error saying that the value would be truncated. It won't write more than the 50 characters you've specified, otherwise you wouldn't be able to prevent the row size from growing out of control
Will SQL Server let me do this? Is it somehow less efficient?
It will emit an error, saying that the string or binary data would be truncated.

Resources