Splitting a datetime and replace the year part - sql

I need to split a date like '01/12/15' and replace the year part from 15 to 2015 (ie; 01-12-2015). I get the year by the sql query:
select YEAR('10/12/15')
It returns the year 2015. but I have to replace 15 to 2015. how do i achieve this.
Anyone here please help me. thanks in advance..
Edited:
I've tried following query too..
declare #date varchar='10/12/2015'
declare #datenew date
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
print #datenew
but it throws some error like this :
Conversion failed when converting date and/or time from character string.
How do I change the varchar to date and replace its year part to 4 digit.. please help me..
DECLARE #intFlag INT,#date varchar(150),#payperiod numeric(18,0),#emp_Id varchar(50)
SET #intFlag = 1
declare #count as int set #count=(select count(*) from #myTable)
WHILE (#intFlag <=#count)
BEGIN
select #emp_Id=Employee_Id from #myTable where rownum=#intFlag
select #date=attendance_date from #myTable where rownum=#intFlag
declare #datenew datetime
SELECT #datenew=convert(datetime,CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103) ,103)
It throws the error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."

As you said your column is in varchar type, try the following
Query
CREATE TABLE #temp
(
dt VARCHAR(50)
);
INSERT INTO #temp VALUES
('01/12/15'),
('02/12/15'),
('03/12/15'),
('04/12/15'),
('05/12/15');
UPDATE #temp
SET dt = REPLACE(LEFT(dt, LEN(dt) - 2)
+ CAST(YEAR(CAST(dt AS DATE)) AS VARCHAR(4)), '/', '-');
SELECT * FROM #temp;
EDIT
While declaring the variable #date you have not specified the length.
Check the below sql query.
declare #date varchar(10)='10/12/2015'
declare #datenew date
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
print #datenew

The simplest way by casting Date object to VARCHAR
SELECT RIGHT(CAST(YEAR('10/12/15') AS VARCHAR), 2)

If you want to change the format and get the varchar try to use:
SELECT CONVERT(varchar(10), CAST('10/12/15' AS DATETIME), 105)
I hope it helps.

What datatype is the value '01/12/15'?
Maybe this will help you:
SELECT YEAR(CAST('10/12/15' AS DATE))

Problem with your query is that you haven't specified length for varchar datatype:
declare #date varchar(12)='10/12/2015'
declare #datenew date
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
print #datenew

Try using:
Declare #date nvarchar(20)='10/12/15'
Declare #datenew nvarchar(40)
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
Print #datenew

Related

It is possible to combine date and time and stored into datetime format

Here what I am trying
CREATE TABLE #date (dt datetime)
declare #date Date ='2019-01-29',
#time time='11:06:31.095',
INSERT INTO #date
SELECT CONVERT(NVARCHAR,CONVERT(NVARCHAR,#date)+' '+CONVERT(NVARCHAR,#time))
It gives error:
Conversion failed when converting date and/or time from character
string.
SQL Server allows you to add datetime values, so you can do:
select convert(datetime, #date) + convert(datetime, #time)
You can try this
CREATE TABLE #date (dt datetime)
declare #date Date ='2019-01-29'
declare #time time='11:06:31.095'
INSERT INTO #date
SELECT CONVERT(datetime,#date)+ CONVERT(datetime,#time)
select * from #date

Convert varchar column to datetime in sql server

I have a table with following definition and data.
Definition:
CREATE TABLE [dbo].[TestTB]
(
[CREATEDATE] [nvarchar](50) NULL
) ON [PRIMARY]
Data:
10/9/2014
1/26/2015
2/16/2015
When I run the query:
Select
CAST(CREATEDATE AS DATETIME) as CREATEDATE
FROM
[dbo].[TestTB]
It is throwing error:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
The above does not work even after running
SET DATEFORMAT dmy
However the following query works fine
DECLARE #data nvarchar(50)
SET #data = ' 10/9/2014 '
Select CAST(#data as DateTime)
Above query returns: 2014-10-09 00:00:00.000
How do I convert a date string (of mm/dd/yyyy format) stored in a column to datetime?
First, if your table column is "DateTime" type than it will save data in this format "2014-10-09 00:00:00.000" no matter you convert it to date or not. But if not so and if you have SQL Server version 2008 or above than you can use this,
DECLARE #data nvarchar(50)
SET #data = '10/9/2014'
IF(ISDATE(#data)>0)
BEGIN
SELECT CONVERT(DATE, #data)
END
Otherwise
DECLARE #data nvarchar(50)
SET #data = '10/9/2014'
IF(ISDATE(#data)>0)
BEGIN
SELECT CONVERT(DATETIME, #data)
END
To Insert into table
INSERT INTO dbo.YourTable
SELECT CREATEDATE FROM
(
SELECT
(CASE WHEN (ISDATE(#data) > 0) THEN CONVERT(DATE, CREATEDATE)
ELSE CONVERT(DATE, '01/01/1900') END) as CREATEDATE
FROM
[dbo].[TestTB]
) AS Temp
WHERE
CREATEDATE <> CONVERT(DATE, '01/01/1900')
DECLARE #data nvarchar(50)
SET #data = ' 10/9/2014 '
SELECT CONVERT(datetime, #data, 101)
SELECT CONVERT(datetime, CREATEDATE, 101) as CREATEDATE
FROM [dbo].[TestTB]
http://www.sqlfiddle.com/#!6/f2103
please check this http://msdn.microsoft.com/en-us/library/aa226054%28SQL.80%29.aspx
Try this out:
SELECT IIF(ISDATE(CREATEDATE) = 1, CONVERT(DATETIME, CREATEDATE, 110), CREATEDATE) as DT_CreateDate
FROM [dbo].[TestTB]
SQL Fiddle Solution
nvarchar to datetime is an implicit conversion, it means you can do this:
declare #strDate nvarchar(50), #myDate datetime
set #strDate = '01/26/2013'
set #myDate = #strDate
But your problem is date format so you have to convert it, but you have to scpecify the format or style and the code of the style you're using is 101 (according to this table) so the secure way:
declare #strDate nvarchar(50), #myDate datetime
set #strDate = '01/26/2013'
set #myDate = CONVERT(DATETIME, #strDate, 101)
You can skip the code but with diferent configuration(server) that code will break.
If you use the ISO style (yyyymmdd) you never would'nt have to worry and the conversion would be implicit:
declare #strDate nvarchar(50), #myDate datetime
set #strDate = '20150421' --ISO style (yyyymmdd)
set #myDate = #strDate

Convert datetime and varchar to single date

I have a following database columns and the values
MyDate datetime and My_Time varchar(5)
the values stored are
2006-09-05 00:00:00.000 and 16:47
Now I want to add this two columns and get a single datetime value 2006-09-05 16:47:00.000
How can I do this in SQL ?
UPDATE:
Some rows have NULL values for DocDate and DocTime.
So i am getting error like Conversion failed when converting date and/or time from character string
Simply...
DECLARE #date DATETIME
DECLARE #time VARCHAR(5)
SET #date = '2006-09-05 00:00:00.000'
SET #time = '16:47'
SELECT CAST(#date + #time AS DATETIME) -- 2006-09-05 16:47:00.000
Try this:
select dateadd(ss, datediff(ss, 0, #My_Time), #MyDate)
Key point is to understand that it's the same as...
select dateadd(ss, datediff(ss, 0, cast(#My_Time as time)), #MyDate)
...but the conversion is done explicitly.
EDIT
For default time and/or date, use ISNULL or COALESCE as appropriate.
Example:
SELECT
CAST(
isnull(#date, '2000-1-1') +
isnull(#time, '0:0')
AS DATETIME)
Try
CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME) as CombinedDate

How to add 1 day to current date and have result in format yyyymmdd in SQL Server?

I need to add 1 day to the current date and have the output in the format yyyymmdd.
The code needs to be written on a stored procedure on the sql server.
currently my code is as follows:
DECLARE #dat DATE
select #dat = dateadd(DD, 1, getdate())
SELECT #dat =LEFT(CONVERT(VARCHAR(8), #dat, 112),10)
However, it seems like im doing something wrong as my output on the sql table is in the format yyyy-mm-dd. I need to get rid of the hyphens.
any suggestions guys? thanks in advance.
The issue is that you are assigning it back to a date object. You need to assign it to a varchar.
I did the following in SQL Server 2005:
DECLARE #dat DATETIME
DECLARE #string varchar(8)
SET #dat = GetUtcDate()
select #dat = dateadd(DD, 1, getdate())
SELECT #string =CONVERT(VARCHAR(8), #dat, 112)
PRINT #string
Change the declaration of #dat to a STRING
Try this one -
DECLARE #date VARCHAR(8)
SELECT #date = CONVERT(VARCHAR(8), DATEADD(DAY, 1, GETDATE()), 112)
SELECT #date
select #dat = dateadd(DD, 1, getdate())
DECLARE #datCus varchar(8)
select #datCus=LEFT(CONVERT(VARCHAR(8), #dat, 112),10)
The problem was that i assigned #dat to the insert statements values. However having a varchar variable to handle the converting part solved the problem (in this case #datCus).

How to convert DateTime to a number with a precision greater than days in T-SQL?

Both queries below translates to the same number
SELECT CONVERT(bigint,CONVERT(datetime,'2009-06-15 15:00:00'))
SELECT CAST(CONVERT(datetime,'2009-06-15 23:01:00') as bigint)
Result
39978
39978
The generated number will be different only if the days are different. There is any way to convert the DateTime to a more precise number, as we do in .NET with the .Ticks property?
I need at least a minute precision.
Well, I would do it like this:
select datediff(minute,'1990-1-1',datetime)
where '1990-1-1' is an arbitrary base datetime.
SELECT CAST(CONVERT(datetime,'2009-06-15 23:01:00') as float)
yields 39977.9590277778
DECLARE #baseTicks AS BIGINT;
SET #baseTicks = 599266080000000000; --# ticks up to 1900-01-01
DECLARE #ticksPerDay AS BIGINT;
SET #ticksPerDay = 864000000000;
SELECT CAST(#baseTicks + (#ticksPerDay * CAST(GETDATE() AS FLOAT)) AS BIGINT) AS currentDateTicks;
If the purpose of this is to create a unique value from the date, here is what I would do
DECLARE #ts TIMESTAMP
SET #ts = CAST(getdate() AS TIMESTAMP)
SELECT #ts
This gets the date and declares it as a simple timestamp
Use DateDiff for this:
DateDiff (DatePart, #StartDate, #EndDate)
DatePart goes from Year down to Nanosecond.
More here.. http://msdn.microsoft.com/en-us/library/ms189794.aspx
And here is a bigint version of the same
DECLARE #ts BIGINT
SET #ts = CAST(CAST(getdate() AS TIMESTAMP) AS BIGINT)
SELECT #ts
CAST to a float or decimal instead of an int/bigint.
The integer portion (before the decimal point) represents the number of whole days. After the decimal are the fractional days (i.e., time).
You can use T-SQL to convert the date before it gets to your .NET program. This often is simpler if you don't need to do additional date conversion in your .NET program.
DECLARE #Date DATETIME = Getdate()
DECLARE #DateInt INT = CONVERT(VARCHAR(30), #Date, 112)
DECLARE #TimeInt INT = REPLACE(CONVERT(VARCHAR(30), #Date, 108), ':', '')
DECLARE #DateTimeInt BIGINT = CONVERT(VARCHAR(30), #Date, 112) + REPLACE(CONVERT(VARCHAR(30), #Date, 108), ':', '')
SELECT #Date as Date, #DateInt DateInt, #TimeInt TimeInt, #DateTimeInt DateTimeInt
Date DateInt TimeInt DateTimeInt
------------------------- ----------- ----------- --------------------
2013-01-07 15:08:21.680 20130107 150821 20130107150821