Search code examples
sql-servert-sqlconcatenationstring-concatenation

Script to create an insert SQL


I'm trying to create a script that concatenate various values that in the end it creates a insert script,i'm already made one.

INSERT INTO #SCRPTS
SELECT getdate(),
    'INSERT WKF_TpProcesso VALUES (''' + Des_TpProcesso + ''',' + cast(Cod_Func as Varchar(8)) + ',getdate() ,null ,1 ,' + CASE WHEN Id_Sistema IS NULL THEN 'Null' ELSE CAST(Id_Sistema as Varchar(6)) END 
    +',0,1,0,'+ CASE WHEN Des_CodigoTpProcesso IS NULL THEN 'Null' ELSE '''' + Des_CodigoTpProcesso  END  +''''+ ','+CAST(Flg_ProxProcesso as Varchar(1))''')'
FROM WKF_TpProcesso 
WHERE Des_CodigoTpProcesso =  @Des_CodigoTpProcesso

The result is this:

INSERT WKF_TpProcesso VALUES ('Processo Teste',41815,getdate() ,null ,1 ,169,0,1,0, 'PcTestPlus',1)

I'm doing another but can't figure out why doesn't work.

WHILE (exists (select Id_EtapaCampoGen from WKF_EtapaCampoGen Where Id_Etapa = @Id_Etapa ))  

    INSERT INTO #SCRPTS
     SELECT getdate(),
      'INSERT WKF_EtapaCampoGen VALUES 
      (@Id_Etapa' +      
      ','+ ''''+ Des_Label + '''' +
      ','+ ''''+ Vl_Identificador + '''' +
      ','+ cast(Flg_Obrigatorio as Varchar(2)) +
      ',getdate(),'+ 
      ',' + CASE WHEN DT_Alteracao IS NULL OR DT_Alteracao = '' THEN 'NULL' ELSE '''' + 
      ',' + cast(FLG_Situacao as Varchar(2))+
      ',' + '''' + Tipo + '''' +
      ',' + '''' + Query + '''' +')'

      FROM WKF_EtapaCampoGen

I'm having error "Incorrect sintax near FROM",but i cant see what is wrong,someone knows ? What is funny is that for example the column Des_Label in this is script the DB find the reference of where it comes from,but if i have the error in the from statment how it can find?


It was a END missing in the case when stament,with the end the script returned this.

INSERT WKF_EtapaCampoGen VALUES 
      (@Id_Etapa,'Areas','CampoComplementar1',0,getdate(),NULL,1,'Lista','select Des_area as Texto, Des_area as valor from wkf_area')

Solution

  • your case expression needs an END

    CASE WHEN DT_Alteracao IS NULL OR DT_Alteracao = '' THEN 'NULL' ELSE '''''' END