Doubt - Update SQL Server 2012

0

When the update below is run for the first time, the field exits correctly the way I want it as below, but if I run it again, it comes out that way. What I want is that regardless of how many times the script runs, do not duplicate the month or year.

  

(WRONG)   Esttartitulo   Strategic Assisted ProductionOctober 2017October-2017

     

(CORRECT)   Esttartitulo   Strategic Assisted ProductionOctober 2017

Update script

UPDATE EstoqueTarefa
SET EstTarTitulo = (SELECT CONCAT(EstTarTitulo,DATENAME(MONTH,getdate()),'-',DATEPART(YEAR,getdate()))) 
WHERE EstTarID = 246
    
asked by anonymous 16.10.2017 / 16:07

3 answers

0

Declare a support table, populate it and use it to check if the title already has a month included:

DECLARE @meses TABLE(numero INT,
                     nome   VARCHAR(10));
DECLARE @data_base DATE,
        @mes       VARCHAR(10),
        @ano       INT;

SET @data_base = DATEADD(MONTH, 1, GETDATE());

INSERT INTO @meses
VALUES(1, 'JANEIRO'),
      (2, 'FEVEREIRO'),
      (3, 'MARÇO'),
      (4, 'ABRIL'),
      (5, 'MAIOR'),
      (6, 'JUNHO'),
      (7, 'JULHO'),
      (8, 'AGOSTO'),
      (9, 'SETEMBRO'),
      (10, 'OUTUBRO'),
      (11, 'NOVEMBRO'),
      (12, 'DEZEMBRO');

SELECT @mes = m.nome,
       @ano = DATEPART(YEAR, @data_base)
  FROM @meses m
 WHERE m.numero = DATEPART(MONTH, @data_base);

UPDATE et
   SET et.EstTarTitulo = EstTarTitulo + ' ' + @mes + ' - ' + CAST(@ano AS VARCHAR)
  FROM EstoqueTarefa et
 WHERE EstTarID = 246
   AND NOT EXISTS(SELECT 1
                    FROM @meses m
                   WHERE et.EstTarTitulo LIKE '%' + m.nome + '%')
    
17.10.2017 / 21:28
1

You can do this too

declare @MesAno varchar(50);
set @MesAno = (SELECT DATENAME(MONTH,getdate()) + '-' + Convert(varchar, DATEPART(YEAR,getdate())) as MesAno)

UPDATE  EstoqueTarefa
SET     EstTarTitulo = EstTarTitulo + @MesAno
WHERE   EstTarID = 246 AND CharIndex(@MesAno, EstTarTitulo)) = 0
    
16.10.2017 / 16:35
0

charindex should resolve your issue:

declare @MesAno varchar(50)
select @MesAno = CONCAT(DATENAME(MONTH,getdate()),'-',DATEPART(YEAR,getdate()))
select @MesAnoAnterior = CONCAT(DATENAME(MONTH,DATEADD(month, -1, getdate())),'-',DATEPART(YEAR,DATEADD(month, -1, getdate())))

UPDATE EstoqueTarefa
SET EstTarTitulo = (SELECT CONCAT(REPLACE(EstTarTitulo,CONCAT(' ', @MesAnoAnterior),''), ' ', @MesAno)) 
WHERE EstTarID = 246

So it only refreshes the column if it does not contain what you want to add. Since the script is run monthly, you can use the above structure, where

  • REPLACE(EstTarTitulo,CONCAT(' ', @MesAnoAnterior),'') remove title from previous month (if any)
  • (SELECT CONCAT({resultadoDoReplace}, ' ', @MesAno)) updates title value with current month
16.10.2017 / 16:18