Change registration day only

2

Scenario (example):

I have the following table:

ID | TIPO |    DATAINCLUSAO
 1 |  10  | 21/07/2018 09:34:51
 2 |  10  | 11/07/2018 11:15:25
 3 |  11  | 23/07/2018 01:52:31
 4 |  11  | 04/07/2018 23:24:52
 5 |  12  | 25/07/2018 03:43:33

Objective:

I would like to make a update on the day only , leaving everything 01 , for example:

ID | TIPO |    DATAINCLUSAO
 1 |  10  | 01/07/2018 09:34:51
 2 |  10  | 01/07/2018 11:15:25
 3 |  11  | 01/07/2018 01:52:31
 4 |  11  | 01/07/2018 23:24:52
 5 |  12  | 01/07/2018 03:43:33
  • Is there a possibility in the update itself
  • ?
  • If not, what alternatives ?
asked by anonymous 15.08.2018 / 14:23

4 answers

4

Considering that DATAINCLUSAO is of type datetime you can try the following UPDATE :

UPDATE tabela SET datainclusao = CONVERT(
    datetime, FORMAT(datainclusao, 'yyyy-MM-01 H:mm:ss')
);

In the FORMAT function I am formatting the date into a format that datetime will understand by changing the day part.

Then with CONVERT I convert the date back to datetime because the return of FORMAT is nvarchar .

    
15.08.2018 / 14:40
3

You can use the DATEFROMPARTS , to change only the day:

UPDATE tabela 
  SET datainclusao = datefromparts(year(datainclusao), month(datainclusao), 1)

Here, I took the year itself and the month of the date and only set the day as "1", since the function accepts (year, month, day) as parameters.

    
15.08.2018 / 16:43
1

You can update the data by update yes.

You have to turn the date into text, adjust the day, and turn the value back to date.

I know this way, if I have others, I will learn.

Test with SELECT

select 
  '01' + substring(convert(varchar(25), GETDATE(), 103), 3, 8),
  convert(varchar(12), GETDATE(), 114),
  convert(datetime, '01' + substring(convert(varchar(12), GETDATE(), 103), 3, 8), 103) + convert(datetime, convert(varchar(12), GETDATE(), 114), 114)

No UPDATE

update TABELA set DATAINCLUSAO = convert(datetime, '01' + substring(convert(varchar(12), GETDATE(), 103), 3, 8), 103) + convert(datetime, convert(varchar(12), GETDATE(), 114), 114)
    
15.08.2018 / 14:37
1

Complementing responses:

From SQL Server 2012 , there is the function: DATETIMEFROMPARTS

Syntax:

DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )

Example:

UPDATE tabela 
  SET DATAINCLUSAO = DATETIMEFROMPARTS(YEAR(DATAINCLUSAO), MONTH(DATAINCLUSAO), 1, DATEPART(HOUR, DATAINCLUSAO), DATEPART(MINUTE, DATAINCLUSAO), DATEPART(SECOND, DATAINCLUSAO), DATEPART(MILLISECOND, DATAINCLUSAO))

PS: could only use DATEPART to fetch all parts .

Other functions used:

DATEPART

    
15.08.2018 / 21:11