Replace a certain part of the date - sql

We are creating a demo database. So they need me to change a column having all the dates to a particular date.
Replace just the month and day and keep the year as is.
Ex: 03/12/2012, 06/19/1990
Solution: 01/01/2012, 01/01/1990
They want to make the month and date to: 01/01
My Query is as mentione below:
update Tablename set column = REPLACE(column, select substring(column,1,5) from Tablename ,'01/01') ;
but i get an error as mentione below:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '01/01'.
Any help/advice would be appreciated.

Don't change dates with string manipulation. It is guaranteed to break things down the road and it's slower.
UPDATE TableName
SET [column] = DATEADD(year,DATEDIFF(year,0,[column]),0)

as of SQL Server 2012 there is a DATEFROMPARTS function which is perfect for this ...
eg ... with #originalDate DATE, #newMonth INT, #newDay INT you could form your new date like this:
DECLARE #replacedDate Date;
SET #replacedDate = DATEFROMPARTS(
DATEPART(year, #originalDate),
#newMonth,
#newDay
)
your sql is thus:
update Tablename
set column = DATEFROMPARTS(DATEPART(year, column),1,1)
here are the sql server docs:
DATEFROMPARTS
DATEPART

Just remove the erroneous select:
update Tablename
set column = REPLACE(column, substring(column,1,5) from Tablename ,'01/01');
However, it seems like a more appropriate approach would be using the DATEPART function:
UPDATE Tablename
SET column = CAST('01/01/' + CAST(DATEPART(year, column) AS VARCHAR) AS DATETIME)

First of all you need to convert DateTime to VARCHAR if you want to perform String operation on it.
Secondly, you don't need to look for SUBSTRING. Just update DateTime column using DateTime format.
UPDATE TABLE SET ColumnName = CAST('Whatever Date You Want' AS DATETIME)

Related

SQL Update query to replace last 4 characters in column

I am needing to replace the last four characters in a column.
It is currently a year in a char format and I need to replace with the current year.
The code I am using now is successful in removing the old year but is failing to input the new year that is needed.
My Current Code:
DECLARE #NewYear as Char
SELECT #NewYear = cast(YEAR(GETDATE()) as char(4))
UPDATE MyTable
SET ENDDATE = (substring(ENDDATE, -5, len(ENDDATE)) +#NewYear)
WHERE EndDate < StartDate
Original Value - 01/01/2017
Result - 01/01/
Desired Result - 01/01/2020
This is being used in SAS Proc SQl pass through - ANSI Standard SQL
Any help would be appreciated.
Thank you!
There is a problem in the declaration of your variable. It should be declared as char(4) - otherwise it defaults to char(1) and ends up with value '2' instead of 2020.
Also, you can use left instead o substring.
Here is one way to do it:
DECLARE #NewYear as Char(4)
SELECT #NewYear = CAST(YEAR(GETDATE()) as char(4))
UPDATE MyTable
SET ENDDATE = LEFT(ENDDATE , len(ENDDATE) - 4) + #NewYear
WHERE EndDate < StartDate
Note there is little benefit using a variable here. Very likely, the database will optimize the expression and not do the getdate()-based computation for each row.
UPDATE MyTable
SET ENDDATE = LEFT(ENDDATE , len(ENDDATE) - 4) + cast(YEAR(GETDATE()) as char(4))
WHERE EndDate < StartDate
I would suggest:
UPDATE MyTable
SET ENDDATE = STUFF(ENDDATE, 7, 4, DATENAME(year, GETDATE()))
WHERE EndDate < StartDate;
The WHERE clause makes no sense, because you are doing date comparisons.
Note that variables are not helpful here. You don't have to convert anything to a string, if you use DATENAME(), because it returns a string.
I thought for a moment they might be stored as dates, but you would never get 01/01/ as a valid date.

SQl Server Converting to Date fails , DateTime works

I have a table with a varchar(25) column that holds a date value. A typical value is '11/04/2017'.
This query returns 0 rows
select *
from myTable
where isdate(inputDate) = 0
I am trying to find a max on this, using a date sort.
This query returns the expected result
;with gooddates as
(
select
medcomfolder, PatientId, PatientBirthday, InputDate
from
myTable
where
isdate(inputDate) = 1
)
select max(convert(datetime, inputDate))
from gooddates
This query returns an error.
;with gooddates as
(
select
medcomfolder, PatientId, PatientBirthday, InputDate
from
dwhFuData
where
isdate(inputdate) = 1
)
select max(convert(date, inputdate))
from gooddates
This is the returned error
Msg 241, Level 16, State 1, Line 274
Conversion failed when converting date and/or time from character string
The difference between the 2 queries is that the first is converting to a dateTime while the latter is converting to a date.
At this point, I can move forward w/ the dateTime option, but I am left wondering what I am missing.
I have checked that there are no embedded spaces, and all the columns have a len(InputDate) = 10 (there is NO time data included)
I selected distinct values,put them in excel, and did a date function on each row. I was hoping to get a #VALUE on 1 row. All the rows worked.
So there is nothing silly like '02/31/2019' going on.
How can a dateTime conversion pass when a simple date conversion does not?
My guess is that you have values that include a time stamp following the date (based on the fact that isdate() is always zero).
If so, one simple solution would be to use convert(date, left(inputdate, 10)). Another solution uses try_convert():
try_convert(date, inputdate)
To find the offending values:
select inputdate
from dwhFuData
where try_convert(date, inputdate) is null and inputdate is not null;

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 converting Date datatype from Varchar to Date

so I'm trying to convert my date column datatype from varchar to date.
Currently my date is in d/m/yyyy format and I want to convert to standard mm/dd/yyyy
Here's the script that I'm running
update [table]
set [PERIOD]= CONVERT(varchar(20),cast([PERIOD] as date),101)
But I'm getting an error
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
Any tips or am I stuck?
I suggest instead of updating one string date to another format of string date, that you add a new DATE or DATETIME field to store the dates properly.
ALTER [table] ADD Proper_Date DATE
GO
UPDATE [table]
SET Proper_Date = convert(date, [PERIOD], 103)
If you must, you can wrap the above in another CONVERT():
update [table]
set [PERIOD]= CONVERT(varchar(20),convert(date,[PERIOD], 103),101)
I think if you can segregate the day and month and the year by using substring or any other string functions then use the below query
update tableA
set period = convert(datetime,cast(day(1)as varchar)+'/'+cast(MONTH(1)as varchar)+'/2014',102)
Hope its works.
You may have junk value and can get the junk values by executing the following query
SELECT [PERIOD]
FROM YOURTABLE
WHERE ISDATE([PERIOD]) = 0
To avoid junk values and update the rest try the below
update YOURTABLE
set [PERIOD]= CONVERT(varchar(20),cast([PERIOD] as date),101)
WHERE ISDATE([PERIOD]) = 1
Try this.
update [table]
set [PERIOD]= CONVERT(varchar(20),CONVERT(date,[PERIOD] ,103),101)
Problem in your query is
cast([PERIOD] as date)
You cannot directly convert d/m/yyyy format to date. So use 103 style to convert

SQL Server: Add seconds to a datetime field?

This should be a softball for you SQL guys. I know I can add to an int field with something like UPDATE tblUser SET Total=(Total+2) but what is the syntax for adding seconds to a datetime field?
I'm using SQLServer 2008
UPDATE tbluser SET DateField = DATEADD(ss,numOfSeconds,DateField)
Note the first parameter "ss". This shows that you are adding seconds to the date.
Check the docs for more info.
You should look into DATEADD.
DATEADD (datepart , number , date)
or the full update syntax
UPDATE tbl SET YourDateField = DATEADD (ss, 2, YourDateField)