Datetime search in sql - sql

SQL FIDDLE
CREATE TABLE STUDY
(
[ID][INT],
STUDY_DATE VARCHAR(40),
START_TIME VARCHAR (40),
END_TIME VARCHAR (40)
)
INSERT INTO STUDY VALUES(1,'2013-12-23','11:30:00','11:31:00')
SELECT STUDY_DATE,START_TIME,END_TIME
FROM STUDY
WHERE (STUDY_DATE >='2013-12-22'
AND CAST(START_TIME AS DATETIME) >='19:12:01')
AND (STUDY_DATE <='2013-12-23'
AND CAST(END_TIME AS DATETIME) <='13:12:14')
i have to fetch records from table with above criteria..
however my STUDY_DATE criteria is fullfill but START_TIME criteria not.
thats the reason records not fetch from table..
What should i do.

In your example - '11:30:00' IS NOT more or equal '19:12:01' (when casted to datetime, but it doesnt matter).
Do what people suggest - store date as datetime, dont use varchars for it.
Upd:
Ok, if you cant change your table:
SELECT STUDY_DATE,START_TIME,END_TIME
FROM STUDY
WHERE CAST(STUDY_DATE + 'T' + START_TIME AS DATETIME) >='2013-12-22T19:12:01'
AND CAST(STUDY_DATE + 'T' + END_TIME AS DATETIME) <='2013-12-23T13:12:14'

I don't understand why you store your date fields as varchar...
When you cast START_TIME field as DATETIME its representation is YYYY-MM-DD HH:MM:SS.mmm
So you can't compare your casted field with 19:12:01 but you must take the time part (DATEPART function can help you) and then you'll compare with your constant (19:12:01).
I've seen your SqlFiddle. You can't cast as datetime the value 11:30:00.
Solution A: Change the field type (adviced)
Solution B: Compare as string your values, because is a well formed string (not adviced)

Although it's better use proper data types (datetime in this case) if you can't change data types for this fields you can add computed columns and even create indexes on them (for PERSISTED).
CREATE TABLE #STUDY
(
[ID][INT],
STUDY_DATE VARCHAR(40),
START_TIME VARCHAR (40),
END_TIME VARCHAR (40),
START_DATETIME AS CAST(REPLACE(STUDY_DATE,'-','')+' '+START_TIME as datetime),
END_DATETIME AS CAST(REPLACE(STUDY_DATE,'-','')+' '+END_TIME as datetime)
)
INSERT INTO #STUDY VALUES(1,'2013-12-23','11:30:00','11:31:00')
SELECT STUDY_DATE,START_TIME,END_TIME
FROM #STUDY
WHERE START_DATETIME >='20131222 19:12:01'
AND END_DATETIME <='20131223 13:12:14'
drop table #STUDY

Related

Calculate time difference between 2 columns which are in VARCHAR in SQL Server

My table is:
create table Test_Bench
(
id int,
start_time varchar(20),
stop_time varchar(20)
)
My data set is:
insert into Test_Bench
values (1, '20200520070000', '20200520153000');
I want to calculate the difference between my stop_time and start_time in minutes however as the columns are in varchar format I am running into error while converting the varchar to int.
I tried converting the varchar to int, bigint, datetime, timestamp but none of them are working
The table is already existing and has been created without following the proper data types of date and time.
Now as per my analysis I am trying to pull out the Date and time from this and then calculate the difference between the times extracted.
My expected output will be
Difference (2020-05-2020 15:30:00 - 2020-05-2020 07:00:00) = 510 minutes
you can use CAST or CONVERT to Convert varchar to int.
Select (CAST(start_time as int) - CAST(stop_time as int)) from test_bench
Please try this.
A little STUFF() and a TRY_CONVERT()
Example
Declare #YourTable Table ([id] varchar(50),[starttime] varchar(50),[endtime] varchar(50))
Insert Into #YourTable Values
(1,20200520070000,20200520153000)
Select *
,Minutes = DateDiff(MINUTE
,try_convert(datetime,stuff(stuff(stuff(starttime,13,0,':'),11,0,':'),9,0,' '))
,try_convert(datetime,stuff(stuff(stuff(endtime ,13,0,':'),11,0,':'),9,0,' '))
)
from #YourTable
Returns
id starttime endtime Minutes
1 20200520070000 20200520153000 510
A similar question was answered here. For your specific schema, try something like this:
SELECT id,
DATEDIFF(
mi,
CONVERT(DATETIME, STUFF(STUFF(STUFF(start_time,13,0,':'),11,0,':'),9,0,' ')),
CONVERT(DATETIME, STUFF(STUFF(STUFF(stop_time,13,0,':'),11,0,':'),9,0,' '))
) AS DiffInMins
FROM Test_Bench
It would be better if you could convert the dates going into the table, or abstract the conversion into a UDF, but this is the basic idea.
Fix your design, and then this is trivial. There are date and time data types, and you should be using them to store date and time values. Then you just need DATEDIFF:
create table Test_Bench
(
id int,
start_time datetime2(0),
stop_time datetime2(0)
)
insert into Test_Bench
values (1, '2020-05-20T07:00:00', '2020-05-20T15:30:00');
GO
SELECT DATEDIFF(MINUTE, start_time,stop_time)
FROM dbo.Test_Bench;

Datetime column cannot be pesisted

I have this SQL statement to create a table that stores the JSON string data and the event time found in that JSON string.
CREATE TABLE [dbo].[EventLog]
(
[EventID] INT NOT NULL IDENTITY(1,1),
[EventTime] AS CAST(JSON_VALUE(RawEvent, '$.EventTime') AS DATETIME ) PERSISTED,
[RawEvent] NVARCHAR(MAX) NOT NULL
)
However I get the following error below when I run this, I assume SQL Server does not know if the value fits DATETIME? is there a way to get this column defined?
Msg 4936, Level 16, State 1, Line 26
Computed column 'EventTime' in table 'Event' cannot be persisted because the column is non-deterministic.
You can use CONVERT with dates and have deterministic behavior as long as you specify certain date styles. As per the docs here, with the most common JavaScript date formats (since you are converting from JSON), you can use style 126 or 127, which are ISO8601 and ISO8601 with time zone. Your table, then, could be specified like this:
CREATE TABLE [dbo].[EventLog]
(
[EventID] INT NOT NULL IDENTITY(1,1),
[EventTime] AS CONVERT(DATETIME, JSON_VALUE(RawEvent, '$.EventTime'), 126) PERSISTED,
[RawEvent] NVARCHAR(MAX) NOT NULL
)
Alas, this is explained in the documentation:
CAST Deterministic unless used with datetime, smalldatetime, or sql_variant.
You may be able to parse the date and reconstruct the value using datefromparts() or datetimefromparts().

Converting Varchar into Date in data type

I am relatively new to SQL Server so I was wondering how to convert the data type from varchar to date format? I have a few thousands records so I need a query to help to convert the varchar to date in a single query.
I have the date in this format: yyyymmdd, in varchar(8) and I want to convert this into yyyymmdd, in date format.
Is there any queries to help me with this?
For various conversions between VARCHAR and DATETIME have a look at this link.
Actually in your case, since your VARCHAR is in yyyymmdd format, you could just:
convert(datetime, YourVarcharDateField, 112)
Simply Use this Inbuilt CONVERT Function, and Check this Link for formatting Dates
-- Use 101 if you have divider in your date
SELECT convert(datetime, '2014-01-02',101) as [DateTime]
-- Use 112 if you don't have divider in your date
SELECT convert(datetime, '20140131',112) as [DateTime]
Edited:
UPDATE yourTable SET field = convert(datetime, 'yourFieldName',112)
--This will update all of your field regardless of any particular row
--If you want to update any particular set of rows use `WHERE` clause
if you have more various formats goto to the given link.
Data types can be converted either implicitly or explicitly.
Implicit conversions are not visible to the user. SQL Server automatically converts the data from one data type to another. For example, when a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds.
Explicit conversions use the CAST or CONVERT functions.
The CAST and CONVERT functions convert a value (a local variable, a column, or another expression) from one data type to another
convert(datetime, '2013-05-04',101)
CAST ( expression AS data_type )
ALTER TABLE [dbo].[table] ADD ConvertedDate Date
UPDATE [dbo].[SysData] SET ConvertedDate = CAST(VarCharDate as Date)
ALTER TABLE [dbo].[table] DROP COLUMN VarCharDate
Use CAST OR CONVERT function to convert string to date
Try this:
SELECT CAST('20140102' AS DATE) AS convertedDate;
SELECT CAST(colName AS DATE) AS convertedDate FROM tableA; -- Replace column name and table name
OR
SELECT CONVERT(DATE, '20140102', 112) AS convertedDate;
SELECT CONVERT(DATE, colName, 112) AS convertedDate FROM tableA; -- Replace column name and table name
OUTPUT of both queries:
|convertedDate|
|-------------|
|2014-01-02 |
In SQL SERVER, there are two types of built in conversion techniques.
Convert
Cast
Convert having its own defaults so it will be outdated in upgraded version of SQL SERVER
better make use of CAST Conversion technique
In your scenario.Already having the date with datatype of Varchar(8) trying to Convert into Date
Solve in systematic manner.
Adding the one new Column in the existing table.
Alter Table Table_name Add changedDataTypeDate Date
Update the values in varchar datatype to Date Datatype
UpDate Table_name Set ChangedDataTypeDate = CAST(OriginalDataTypeDate as Date)
Again change the new column name into old column name.
Sp_Rename 'Tablename.changedDataTypeDate','OriginalDataTypeDate','COLUMN'
Its done.
Based on u r requirement.
Alter Table customer Add Purchase_Changedtype Date
Update Customer set Purchase_changedtype = CAST(Purchase_date as Date)
(If u need Time also replace Datetime istead of Date)
Alter table Customer Drop column Purchase_date
Sp_Rename 'Customer.Purchase_ChangedType','Purchase_Date','Column'

how to take specific string with getdate function in sql

i have one crm application. i want to store conversions date and specific time at which time that thread created that to show. how ever i have also one [datetime] column but time is not correct. event though this time part should be default from sql. how ever i want this time part is accurate and how i implement this. is that way to store acuurate time part from sql.
is that way to store time part from getdate function of sql.
for more reference i put table
Inquiry_id varchar(50)
Inquiry_subject varchar(50)
Service_id numeric(18, 0)
Priority_id numeric(18, 0)
User_id varchar(50)
Status_id numeric(18, 0)
body varchar(1024)
Email_Address varchar(50)
IsDisplay bit
IsRead bit
IsReplied bit
TimeStamp datetime
Activity_start_time datetime
Activity_expire_time datetime
please help me..
To display your DateTime columns as Date and separate Time columns, do this in a SELECT statement (or in a view)
SELECT
CONVERT(VarChar(20), Activity_Start_Time, 108) AS ActivityStartTime,
CONVERT(VarChar(30), Activity_Start_Time, 101) AS ActivityStartDateUS
FROM YourExampleTableAbove
This will produce a result like
ActivityStartTime ActivityStartDateUS
----------------- -------------------
08:10:27 4/23/2013
15:58:40 4/29/2013
For more options, read about the Convert() function for TSQL http://msdn.microsoft.com/en-us/library/ms187928.aspx

how to insert multiple values which is the output of a select query

Select
cast(ltrim(rtrim(Substring(string,charindex('my',string)+len('my')+5,
charindex('for the company',string)-charindex('my',string)+len('my')-9))) as datetime)
from table
Select
cast(ltrim(rtrim(Substring(string,charindex('company',string)+len('company')+1,
len(String)-charindex('company',string)+len('company')-9)))as varchar)
from description
this 2 queries has a set of rows as output.
I want to insert these values to another table using single insert.
What i did is:
insert into table2(orderid,orderdate)
Select
cast(ltrim(rtrim(Substring(String, len('The order number')+1,
CHARINDEX ( 'as been created at', String) - len ('as been created at')))) as int)
,
cast(ltrim(rtrim(Substring(string,charindex('at',string)+len('at')+5,
charindex('for the company',string)-charindex('at',string)+len('at')-9))) as datetime)
from description
but its not inserted..its showing error like The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value..
Is there any another way to insert this?
when inserting a datetime you should specify a string that is SQL compliant i.e.
'YYYY-MM-DD HH:MM:SS'
I suspect that the CAST function cant convert the type specified. However you dont need to convert to a datetime, you can simply insert the string representation of the datetime.
Other issues you may encounter are the casting of ltrim(rtrim()) to an int. LTRIM, RTRIM both return a varchar. CHARINDEX already returns an int.
Ensure your types are consistent
To insert output from your two queries into a single table, the data types and number of columns from these queries should match with that of the table. You can use convert
CONVERT(
DATETIME,ltrim(rtrim(Substring(
string,charindex('at',string)+len('at')+5,
charindex('for the company',string)-charindex('at',string)+len('at')-9)))
,112)
for your datetime column and try (provided your target table has a datetime column for OrderDate).