concatenation of date and time and format it - sql-server-2012

I have a below data set.
Create table #table
(
id int,
filedate int,
filedate_time datetime2
)
Insert into #table
select 1,20190801,'8/1/2019 1:33:25 PM'
union
select 2,20190802,'8/2/2019 2:40:25 PM'
union
select 3,20190803,'8/3/2019 1:33:25 PM'
select
cast(filedate_time as time) as time_only,
cast(filedate as varchar(8)) as filedate,
concat(cast(filedate as varchar(8)), ' ', cast(filedate_time as time)) as concatfield
from
#table
I would like to concatenate time from filedate_time and date from filedate and format them in yyyyMMdd-hh:mm:ss.fff.
I cannot use FORMAT function as it says first argument shouldn't be varchar. I am not able to convert concat field into datetime2. it gives me error saying cannot convert string to datetime. I cannot change the source data types.
Can anyone please help me to get the right format?
I want concatfield to be "20190805-3:50:55 PM"

As #Larnu said you "should leave formatting to the presentation layer" and leave basic data in the database. However if you REALLY have to do this for some reason try:
select CONCAT(cast(filedate as varchar(8)), '-', FORMAT(filedate_time,'hh:mm tt'))
from #table

Related

SQL Server : change date format

I need to change the date format from 'yyyy-mm-dd' to 'dd.mm.yyyy'.
I have data in my table like this '2018-08-08', I need convert it to '08.08.2018'.
I have tried:
UPDATE daily_tasks
SET date = REPLACE(date, date, CONVERT(VARCHAR(255), daily_tasks.date, 102))
WHERE 1;
But, it doesn't work.
Ideally you should be storing your dates as bona-fide date columns, not as text. That being said, the date text '2018-08-08' is in fact in an ISO format, and would still allow you to do things like sort and compare against other date literals, so it is not so bad.
But converting this text to a '08.08.2018' format is the wrong thing to do. If a anything, you might want to consider adding a new date column new_date to store this date information. Do that, and then populate it with:
UPDATE daily_tasks
SET new_date = TRY_CONVERT(datetime, date);
Store your date as DATE datatype and when you read data from database use
DECLARE #myDate DATE = '2018-08-08'
SELECT FORMAT(#myDate, 'dd.MM.yyyy')
SELECT CONVERT(VARCHAR(10), #myDate, 104)
Your syntax looks like SQL Sever, so i would do :
UPDATE daily_tasks
SET Col = REPLACE(CONVERT(VARCHAR(10), daily_tasks.date, 103), '/', '.')
WHERE . . . ;
However, i would not recommend to do this, just use CONVERT() with SELECT statement whenever necessary :
SELECT REPLACE(CONVERT(VARCHAR(10), daily_tasks.date, 103), '/', '.')
Regardless of the database, dates are stored in an internal format. This is the correct way to store dates. Do not store dates as strings.
You can specify the format when you query:
CONVERT(VARCHAR(255), daily_tasks.date, 102)
Or, you can even add a computed column to provide this information:
alter table daily_tasks
add date_display as ( CONVERT(VARCHAR(255), daily_tasks.date, 102) ) ;
You could convert the date column to a varchar to store the date in your specified format. However I strongly recommend against this. You should leave it stored as a date.
If you want to do a SELECT to get the data out then you can convert it to your specified format like this:
SELECT CONVERT(VARCHAR, daily_tasks.date, 4)

How to split dash-separated values in SQL Server

I have a date saved in an nvarchar type and I want to split the day, month and year into separate nvarchar variables (that means three variables). The date looks as follows: exposure_date ='2018-12-04' and the format is yyyy-dd-mm
any help please?
My whole project is stuck on this.
The "correct" answer here is to fix your datatype. When storing data always choose an appropriate data type for the data you're storing. For a date (with no time part) then the correct datatype is date. if you're storing numerical data, then use a numerical datatype, such as int or decimal. (n)varchar is not a one size fits all datatype and using it to store data that has a data type designed for it is almost always a bad choice. I'm storing the data as an (n)varchar because I need it in a specific format is never an excuse; have your presentation layer handle to display format, not your RDBMS.
The first step, therefore would be to change your string representation yyyy-dd-MM of a date to the ISO format yyyyMMdd by doing:
UPDATE YourTable
SET exposure_date = LEFT(exposure_date,4) + RIGHT(exposure_date,2) + SUBSTRING(exposure_date,6,2);
Now you have a unambiguous representation, you can change the data type of your column without concerns of incorrect implicit casts or error:
ALTER YourTable ALTER COLUMN exposure_date date;
Then, finally, you can treat your data as what it is, a date, and use the DATEPART function:
SELECT DATEPART(YEAR,exposure_date) AS Exposure_Year,
DATEPART(MONTH,exposure_date) AS Exposure_Month,
DATEPART(DAY,exposure_date) AS Exposure_Day
FROM YourTable;
You can also try the following
Declare #myDate date
select #myDate= Cast(substring('2011-29-12', 1, 4)
+ '-' + substring('2011-29-12', 9, 2)
+ '-' + substring('2011-29-12', 6, 2)
as Date) --YYYY-MM-DD
Select #myDate as DateTime,
datename(day,#myDate) as Date,
month(#myDate) as Month,
datename(year,#myDate) as Year,
Datename(weekday,#myDate) as DayName
The output is as shown below
DateTime Date Month Year DayName
--------------------------------------------
2011-29-12 29 12 2011 Thursday
You can find the live demo here
You can try below -
select concat(cast(year(cast('2018-12-04' as date)) as varchar(4)),'-',
cast(month(cast('2018-12-04' as date)) as varchar(2)), '-',
cast(day(cast('2018-12-04' as date)) as varchar(2)))
from tablename
If you have fixed format, then you could use this simple query with substring method:
select substring(dt, 1, 4) + '-' +
substring(dt, 9, 2) + '-' +
substring(dt, 6, 2) [YYYY-MM-DD]
from (values ('2018-31-12')) tbl(dt)
Let's go directly to the main issue, which is you are using the wrong datatype to store dates, you should store them as DATE, the datatypes are there for a reason and you need to choose a proper one for your column.
So, you need to ALTER your table and change the column datatype to DATE instead of NVARCHAR datatype.
ALTER <Table Name Here>
ALTER COLUMN <Column Name Here> DATE;
Then all things will easy, you just run the following query to get the desired output
SELECT YEAR(<Column Name Here>) TheYear,
MONTH(<Column Name Here>) TheMonth,
DAY(<Column Name Here>) TheDay
FROM <Table Name Here>
Which is the right and the best solution.
You can also (if you are not going to alter your table) do as
CREATE TABLE Dates(
StrDate NVARCHAR(10)
);
INSERT INTO Dates VALUES
(N'2018-12-04'),
(N'Invalid');
SELECT LEFT(StrDate, 4) StrYear,
SUBSTRING(StrDate, 6, 2) StrMonth,
RIGHT(StrDate, 2) StrDay
FROM Dates;
OR
SELECT YEAR(StrDate) StrYear,
MONTH(StrDate) StrMonth,
DAY(StrDate) StrDay
FROM (
SELECT TRY_CAST(StrDate AS DATE) StrDate
FROM Dates
)T

SQL Server CONVERT and CAST not returning the correct date format

I have a table in SQL Server with a column RGSTR_DATE that is of varchar(10) data type, and it has values like 2016-01-23, 1998-08-12, etc...
I want to select and convert those values to 20160123, 19980812, etc...
I tried running these queries:
SELECT CONVERT(DATE, CAST(RGSTR_DATE AS DATE), 112)
FROM [project].[dbo].[my_table];
SELECT CONVERT(VARCHAR(10), RGSTR_DATE, 112)
FROM [project].[dbo].[my_table];
But the results that came back were still 2016-01-23, 1998-08-12 etc...
What am I doing wrong?
Did you try
SELECT CONVERT(VARCHAR(10),cast(RGSTR_DATE as date),112)
You're converting a varchar to a date, but all you need to do is remove the hyphens.
SELECT REPLACE(RGSTR_DATE, '-', '')
FROM [project].[dbo].[my_table]

How to update/Change the date format to MM/dd/yyyy from dd/MM/yyyy format in sql server?

In my db DOB is saved in dd/mm/yyyy format. i want to change the DOB date format to MM/dd/yyyy. How can i do that?
First i want to know which datatype you are using for saving your date value. There is nothing provided with your code no sample code, table details nothing. anyway
i think your 'date of birth' field datatype is datetime,then you can use the following example
create table checktable(
ID int,
name nvarchar (30),
dob datetime);
Example data insert into the table
insert into checktable(ID,name,dob) values(10,'myname','03/01/2014');
//..........
select * from checktable
//Use CONVERT() it will give you the desired output
SELECT TOP 1 ID, dob,CONVERT(varchar,dob,101) 'mm/dd/yyyy'
FROM checktable
UPDATE
if your datatype is varchar and now it is in the format mm/dd/yyyy and you want to change it into dd/mm/yyyy format then use the following example it will help you
create table checktable1(
ID int,
name nvarchar (30),
dob varchar(20));
// insert sample data
insert into checktable1(ID,name,dob) values(10,'myname','21/05/2010');
select * from checktable1
// change the format using substring()
select * FROM checktable1
select dob,substring(dob,4,3)+substring(dob, 1, 3)+substring(dob, 7, 4) from checktable1
It will give you result in 05/21/2010 (mm/dd/yyyy)format
Microsoft SQL: https://msdn.microsoft.com/en-us/library/ms187928.aspx
Syntax for CONVERT:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
use example:
SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY]
For other databases search Date and Time Functions in documentation.
The CONVERT() function is a general function that converts an expression of one data type to another.
The CONVERT() function can be used to display date/time data in different formats.
http://www.w3schools.com/sql/func_convert.asp
if your data type is DateTime then no need to convert it, in later you can convert its format as you want but if your are using varchar or nvarchar
then you can use CONVERT() as below
SELECT convert(datetime, '23/10/2016', 103)
Result : 2016-10-23 00:00:00.000
if just want to conver in date then
SELECT convert(date, '23/10/2016', 103)
Result : 2016-10-23
for more information and other formats
http://www.sqlusa.com/bestpractices/datetimeconversion/
and if you just want to convert string to sting then
SELECT CONVERT(varchar,'23/10/2016',101)
Result : 23/10/2016
This is the query to show all data in dd/mm/yyyy format.Type your column name that contains date in place of datecolumnname and your table name in place of tablename in below query:
select convert(varchar,datecolumname,103) as datecolumname from tablename

Combining (concatenating) date and time into a datetime

Using SQL Server 2008, this query works great:
select CAST(CollectionDate as DATE), CAST(CollectionTime as TIME)
from field
Gives me two columns like this:
2013-01-25 18:53:00.0000000
2013-01-25 18:53:00.0000000
2013-01-25 18:53:00.0000000
2013-01-25 18:53:00.0000000
.
.
.
I'm trying to combine them into a single datetime using the plus sign, like this:
select CAST(CollectionDate as DATE) + CAST(CollectionTime as TIME)
from field
I've looked on about ten web sites, including answers on this site (like this one), and they all seem to agree that the plus sign should work but I get the error:
Msg 8117, Level 16, State 1, Line 1
Operand data type date is invalid for add operator.
All fields are non-zero and non-null. I've also tried the CONVERT function and tried to cast these results as varchars, same problem. This can't be as hard as I'm making it.
Can somebody tell me why this doesn't work? Thanks for any help.
Assuming the underlying data types are date/time/datetime types:
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112)
+ ' ' + CONVERT(CHAR(8), CollectionTime, 108))
FROM dbo.whatever;
This will convert CollectionDate and CollectionTime to char sequences, combine them, and then convert them to a datetime.
The parameters to CONVERT are data_type, expression and the optional style (see syntax documentation).
The date and time style value 112 converts to an ISO yyyymmdd format. The style value 108 converts to hh:mi:ss format. Evidently both are 8 characters long which is why the data_type is CHAR(8) for both.
The resulting combined char sequence is in format yyyymmdd hh:mi:ss and then converted to a datetime.
The simple solution
SELECT CAST(CollectionDate as DATETIME) + CAST(CollectionTime as DATETIME)
FROM field
An easier solution (tested on SQL Server 2014 SP1 CU6)
Code:
DECLARE #Date date = SYSDATETIME();
DECLARE #Time time(0) = SYSDATETIME();
SELECT CAST(CONCAT(#Date, ' ', #Time) AS datetime2(0));
This would also work given a table with a specific date and a specific time field. I use this method frequently given that we have vendor data that uses date and time in two separate fields.
Cast it to datetime instead:
select CAST(CollectionDate as DATETIME) + CAST(CollectionTime as TIME)
from field
This works on SQL Server 2008 R2.
If for some reason you wanted to make sure the first part doesn't have a time component, first cast the field to date, then back to datetime.
DECLARE #ADate Date, #ATime Time, #ADateTime Datetime
SELECT #ADate = '2010-02-20', #ATime = '18:53:00.0000000'
SET #ADateTime = CAST (
CONVERT(Varchar(10), #ADate, 112) + ' ' +
CONVERT(Varchar(8), #ATime) AS DateTime)
SELECT #ADateTime [A nice datetime :)]
This will render you a valid result.
Solution (1): datetime arithmetic
Given #myDate, which can be anything that can be cast as a DATE, and #myTime, which can be anything that can be cast as a TIME, starting SQL Server 2014+ this works fine and does not involve string manipulation:
CAST(CAST(#myDate as DATE) AS DATETIME) + CAST(CAST(#myTime as TIME) as DATETIME)
You can verify with:
SELECT GETDATE(),
CAST(CAST(GETDATE() as DATE) AS DATETIME) + CAST(CAST(GETDATE() as TIME) as DATETIME)
Solution (2): string manipulation
SELECT GETDATE(),
CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112) + ' ' + CONVERT(CHAR(8), GETDATE(), 108))
However, solution (1) is not only 2-3x faster than solution (2), it also preserves the microsecond part.
See SQL Fiddle for the solution (1) using date arithmetic vs solution (2) involving string manipulation
Concat date of one column with a time of another column in MySQL.
SELECT CONVERT(concat(CONVERT('dateColumn',DATE),' ',CONVERT('timeColumn', TIME)), DATETIME) AS 'formattedDate' FROM dbs.tableName;
drop table test
create table test(
CollectionDate date NULL,
CollectionTime [time](0) NULL,
CollectionDateTime as (isnull(convert(datetime,CollectionDate)+convert(datetime,CollectionTime),CollectionDate))
-- if CollectionDate is datetime no need to convert it above
)
insert test (CollectionDate, CollectionTime)
values ('2013-12-10', '22:51:19.227'),
('2013-12-10', null),
(null, '22:51:19.227')
select * from test
CollectionDate CollectionTime CollectionDateTime
2013-12-10 22:51:19 2013-12-10 22:51:19.000
2013-12-10 NULL 2013-12-10 00:00:00.000
NULL 22:51:19 NULL
This works in SQL 2008 and 2012 to produce datetime2:
declare #date date = current_timestamp;
declare #time time = current_timestamp;
select
#date as date
,#time as time
,cast(#date as datetime) + cast(#time as datetime) as datetime
,cast(#time as datetime2) as timeAsDateTime2
,dateadd(dayofyear,datepart(dayofyear,#date) - 1,dateadd(year,datepart(year,#date) - 1900,cast(#time as datetime2))) as datetime2;
dealing with dates, dateadd must be used for precision
declare #a DATE = getdate()
declare #b time(7) = getdate()
select #b, #A, GETDATE(), DATEADD(day, DATEDIFF(day, 0, #a), cast(#b as datetime2(0)))
I am using SQL Server 2016 and both myDate and myTime fields are strings. The below tsql statement worked in concatenating them into datetime
select cast((myDate + ' ' + myTime) as datetime) from myTable
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), date, 112) + ' ' + CONVERT(CHAR(8), time, 108))
FROM tablename