├── 01_Convert_Substring.sql ├── 02_Convert_Datas.sql ├── 02_Views ├── 01_Create_View.sql └── Views ├── 03_Processos_Ativos.sql ├── 04_Tempo_Entre_DatasHoras.sql ├── Functions ├── 1 ├── 06_Functions_Replace.sql └── 09_Function_DiaUtil.sql ├── Grants ├── 01_Grants_Users.sql └── Grants ├── Procedures ├── 1 ├── 03_Consulta_Conteudos_Procedures.sql ├── 05_Create_Procedure.sql ├── 07_Procedure_Cursor.txt └── 10_Procedure_Average_Calculation.sql ├── README.md ├── SQL_Json ├── 01_Importar_Arquivo_JsonSQL.sql ├── 03_Importar_Json_Git.sql └── SQL_Json └── Tables ├── 01_Create_Tabel.sql ├── 02_Alter_Table_addfield.sql ├── 03_Drop_Table.sql ├── 04_Drop_Field.sql └── Tables /01_Convert_Substring.sql: -------------------------------------------------------------------------------- 1 | 2 | ALTER procedure [dbo].[spcr_operacao_corretora] 3 | @dt_carga smalldatetime 4 | as 5 | begin try 6 | 7 | declare @nm_arquivo varchar(255); 8 | declare @qt_regi_ins int; 9 | declare @qt_regi_upd int; 10 | declare @cd_carga int; 11 | declare @dt_inicio smalldatetime; 12 | declare @dt_termino smalldatetime; 13 | 14 | 15 | --Limpa tabela temporaria corretora 16 | delete from dbo.ttp_operacao_corretora; 17 | 18 | --Em 02/02/2023: Limpa tabela temporaria corretora benchmark 19 | 20 | delete from dbo.ttp_operacao_corretora_benchmark 21 | 22 | --Seta o nome do arquivo 23 | set @nm_arquivo = 'Operacao_Corretora' + upper(convert(varchar(8), @dt_carga,112)) + '.TXT'; 24 | set @dt_inicio = getdate(); 25 | set @dt_termino = getdate(); 26 | 27 | --Em 02/02/2023: Criar Variavel para capturar dia util anterior 28 | 29 | declare @dt_diaUtilAnterior smalldatetime; 30 | 31 | select @dt_diaUtilAnterior = (Select dbo.fncDia_Util_Anterior (@dt_carga, 1)) 32 | 33 | --Obtem o codigo da carga 34 | exec @cd_carga = dbo.spgr_obter_cd_carga 10, @dt_carga, @nm_arquivo, 'spcr_operacao_corretora', @dt_inicio, @dt_termino, 0; 35 | 36 | --- Insere registros na tabela temporaria 37 | 38 | INSERT INTO [dbo].[ttp_operacao_corretora] 39 | ([cd_chave] -- 1 40 | ,[dc_operacao] -- 2 41 | ,[dt_ordem] -- 3 42 | ,[nm_cliente] -- 4 43 | ,[cd_bolsa] -- 5 44 | ,[dg_bolsa] -- 6 45 | ,[tp_ordem] -- 7 46 | ,[dt_validade] -- 8 47 | ,[dt_hr_ordem] -- 9 48 | ,[dc_bolsa] -- 10 49 | ,[dc_pesvinc] -- 11 50 | ,[qt_espec] -- 12 51 | ,[vl_preco_papel]-- 13 52 | ,[dc_assessor] -- 14 53 | ,[dc_papel] -- 15 54 | ,[nr_negocio] -- 16 55 | ,[qt_negocio] -- 17 56 | ,[vl_negocio] -- 18 57 | ,[cd_contraparte] -- 19 58 | ,[dg_negocio] -- 20 59 | ,[tp_neg] -- 21 60 | ,[qt_executada] -- 22 61 | ,[dc_observ] -- 23 62 | ,[dc_justif] -- 24 63 | ,[dc_emitente] -- 25 64 | ,[dc_operador] -- 26 65 | ,[dc_cli_qualif] -- 27 66 | ,[dt_pregao] -- 28 67 | ,[dc_hr_neg] -- 29 68 | ,[dc_obs] -- 30 69 | ,[cd_mercado] -- 31 70 | ,[dc_mercado] -- 32 71 | ,[nm_empresa] -- 33 72 | ,[dc_especie] -- 34 73 | ,[pr_exerc] -- 35 74 | ,[dt_venc] -- 36 75 | ,[cd_carga] -- 37 76 | ,[vl_fator_cotacao] -- 38 77 | ,[id_daytrade]) -- 39 78 | Select DISTINCT CHAVE_ORDEM, -- 1 79 | OPERACAO, -- 2 80 | DT_ORDEM, -- 3 81 | CLIENTE, -- 4 82 | CODBOLSA, -- 5 83 | DIGBOLSA, -- 6 84 | TIPO_ORDEM, -- 7 85 | case when cast(DT_VALID as date) > '2079-06-06' then DT_PREGAO else DT_VALID end DT_VALID, -- 8 --tratar limite do campo smalldatetime que e 2079-06-06 86 | DT_HR_ORDEM, -- 9 87 | BOLSA, -- 10 88 | PESVINC, -- 11 89 | QT_ESPEC, -- 12 90 | PRECO_PAPEL, -- 13 91 | ASSESSOR, -- 14 92 | PAPEL, -- 15 93 | NR_NEGOCIO, -- 16 94 | QT_NEGOCIO, -- 17 95 | VL_NEGOCIO, -- 18 96 | CONTRAPARTE, -- 19 97 | DIG_NEGOCIO, -- 20 98 | TIPO_NEG, -- 21 99 | QT_EXECUTADA,-- 22 100 | OBSERV, -- 23 101 | JUSTIF, -- 24 102 | EMITENTE, -- 25 103 | OPERADOR, -- 26 104 | CLI_QUALIF, -- 27 105 | DT_PREGAO, -- 28 106 | HR_NEG, -- 29 107 | DS_OBS, -- 30 108 | COD_MERCADO, -- 31 109 | MERCADO, -- 32 110 | NOME_EMPRESA,-- 33 111 | ESPECIE, -- 34 112 | PR_EXERC, -- 35 113 | DT_VENC, -- 36 114 | @cd_carga, -- 37 115 | FAT_COT, -- 38 116 | case when UPPER(id_daytrade) = 'Y' then 1 else 0 end as id_daytrade -- 39 117 | from OPENQUERY (SINACOR_LS, 118 | ' select * 119 | FROM SIRCOIAPP.VW_ORD_NEGS' ) 120 | where DT_PREGAO = @dt_carga 121 | 122 | --- Em 2023-02-02: Insere registros na tabela temporaria benchmark 123 | 124 | INSERT INTO [dbo].[ttp_operacao_corretora_benchmark] 125 | ([cd_chave] -- 1 126 | ,[dc_operacao] -- 2 127 | ,[dt_ordem] -- 3 128 | ,[nm_cliente] -- 4 129 | ,[cd_bolsa] -- 5 130 | ,[dg_bolsa] -- 6 131 | ,[tp_ordem] -- 7 132 | ,[dt_validade] -- 8 133 | ,[dt_hr_ordem] -- 9 134 | ,[dc_bolsa] -- 10 135 | ,[dc_pesvinc] -- 11 136 | ,[qt_espec] -- 12 137 | ,[vl_preco_papel]-- 13 138 | ,[dc_assessor] -- 14 139 | ,[dc_papel] -- 15 140 | ,[nr_negocio] -- 16 141 | ,[qt_negocio] -- 17 142 | ,[vl_negocio] -- 18 143 | ,[cd_contraparte] -- 19 144 | ,[dg_negocio] -- 20 145 | ,[tp_neg] -- 21 146 | ,[qt_executada] -- 22 147 | ,[dc_observ] -- 23 148 | ,[dc_justif] -- 24 149 | ,[dc_emitente] -- 25 150 | ,[dc_operador] -- 26 151 | ,[dc_cli_qualif] -- 27 152 | ,[dt_pregao] -- 28 153 | ,[dc_hr_neg] -- 29 154 | ,[dc_obs] -- 30 155 | ,[cd_mercado] -- 31 156 | ,[dc_mercado] -- 32 157 | ,[nm_empresa] -- 33 158 | ,[dc_especie] -- 34 159 | ,[pr_exerc] -- 35 160 | ,[dt_venc] -- 36 161 | ,[cd_carga] -- 37 162 | ,[vl_fator_cotacao] -- 38 163 | ,[id_daytrade] -- 39 164 | ,[vl_benchmark]) -- 40 165 | Select DISTINCT CHAVE_ORDEM, -- 1 166 | OPERACAO, -- 2 167 | DT_ORDEM, -- 3 168 | CLIENTE, -- 4 169 | CODBOLSA, -- 5 170 | DIGBOLSA, -- 6 171 | TIPO_ORDEM, -- 7 172 | case when cast(DT_VALID as date) > '2079-06-06' then DT_PREGAO else DT_VALID end DT_VALID, -- 8 --tratar limite do campo smalldatetime que e 2079-06-06 173 | DT_HR_ORDEM, -- 9 174 | BOLSA, -- 10 175 | PESVINC, -- 11 176 | QT_ESPEC, -- 12 177 | PRECO_PAPEL, -- 13 178 | ASSESSOR, -- 14 179 | PAPEL, -- 15 180 | NR_NEGOCIO, -- 16 181 | QT_NEGOCIO, -- 17 182 | VL_NEGOCIO, -- 18 183 | CONTRAPARTE, -- 19 184 | DIG_NEGOCIO, -- 20 185 | TIPO_NEG, -- 21 186 | QT_EXECUTADA,-- 22 187 | OBSERV, -- 23 188 | JUSTIF, -- 24 189 | EMITENTE, -- 25 190 | OPERADOR, -- 26 191 | CLI_QUALIF, -- 27 192 | DT_PREGAO, -- 28 193 | HR_NEG, -- 29 194 | DS_OBS, -- 30 195 | COD_MERCADO, -- 31 196 | MERCADO, -- 32 197 | NOME_EMPRESA,-- 33 198 | ESPECIE, -- 34 199 | PR_EXERC, -- 35 200 | DT_VENC, -- 36 201 | @cd_carga, -- 37 202 | FAT_COT, -- 38 203 | case when UPPER(id_daytrade) = 'Y' then 1 else 0 end as id_daytrade, -- 39, 204 | vl_benchmark -- 40 205 | from OPENQUERY (SINACOR_LS, 206 | ' select * 207 | FROM SIRCOIAPP.VW_ORD_NEGS' ) 208 | where DT_PREGAO = @dt_diaUtilAnterior 209 | 210 | 211 | -- Limpa tbl_operacao_corretora para o reprocessamento 212 | delete tbl_operacao_corretora where dt_pregao = @dt_carga 213 | 214 | -- Limpa tbl_operacao_corretora_ para o reprocessamento 215 | delete tbl_operacao_corretora_benchmark where dt_pregao = @dt_diaUtilAnterior 216 | 217 | --- Insert tbl_operacao_corretora 218 | 219 | insert into tbl_operacao_corretora 220 | (cd_chave, --01 221 | cd_cliente, --02 222 | dc_operacao, --03 223 | dt_ordem, --04 224 | cd_bolsa, --05 225 | dg_bolsa, --06 226 | tp_ordem, --07 227 | dt_validade, --08 228 | dt_hr_ordem, --09 229 | dc_bolsa, --10 230 | dc_pesvinc, --11 231 | qt_espec, --12 232 | vl_preco_papel, --13 233 | dc_assessor, --14 234 | dc_papel, --15 235 | nr_negocio, --16 236 | qt_negocio, --17 237 | vl_negocio, --18 238 | cd_contraparte, --19 239 | dg_negocio, --20 240 | tp_neg, --21 241 | qt_executada, --22 242 | dc_observ, --23 243 | dc_justif, --24 244 | dc_emitente, --25 245 | dc_operador, --26 246 | dc_cli_qualif, --27 247 | dt_pregao, --28 248 | dc_hr_neg, --29 249 | dc_obs, --30 250 | dc_mercado, --31 251 | nm_empresa, --32 252 | dc_especie, --33 253 | pr_exerc, --34 254 | dt_venc, --35 255 | cd_carga, --36 256 | cd_mercado, --37 257 | vl_fator_cotacao, --38 258 | id_daytrade) --39 259 | select distinct 260 | substring(ttp.cd_chave,1,21) as cd_chave, -- 01. cd_chave, --01 261 | cl.cd_cliente, -- 02. cd_cliente, --02 262 | ttp.dc_operacao, -- 03. dc_operacao, --03 263 | convert(smalldatetime,substring(ttp.dt_ordem,1,4) 264 | + substring(ttp.dt_ordem,6,2) 265 | + substring(ttp.dt_ordem,9,2))as dt_ordem, -- 04.dt_ordem, --04 266 | ttp.cd_bolsa, -- 05.cd_bolsa, --05 267 | ttp.dg_bolsa, -- 06.dg_bolsa, --06 268 | ttp.tp_ordem, -- 07.tp_ordem, --07 269 | case when convert(int,right(ttp.dt_validade,1))>= 2079 270 | then CONVERT(smalldatetime,'2079-06-06') else 271 | convert(smalldatetime,substring(ttp.dt_validade,1,4) 272 | + substring(ttp.dt_validade,6,2) 273 | + substring(ttp.dt_validade,9,2)) end as dt_validade, -- 08.dt_validade, --08 274 | convert(smalldatetime,substring(ttp.dt_hr_ordem,1,4) 275 | + substring(ttp.dt_hr_ordem,6,2) + substring(ttp.dt_hr_ordem,9,2) 276 | + ' ' + substring(ttp.dt_hr_ordem,12,8)) as dt_hr_ordem, -- 09.dt_hr_ordem, --09 277 | ttp.dc_bolsa, -- 10.dc_bolsa, --10 278 | ttp.dc_pesvinc, -- 11.dc_pesvinc, --11 279 | ttp.qt_espec, -- 12.qt_espec, --12 280 | ttp.vl_preco_papel, -- 13.vl_preco_papel, --13 281 | ttp.dc_assessor, -- 14.dc_assessor, --14 282 | ttp.dc_papel, -- 15.dc_papel, --15 283 | ttp.nr_negocio, -- 16.nr_negocio, --16 284 | ttp.qt_negocio, -- 17.qt_negocio, --17 285 | ttp.vl_negocio, -- 18.vl_negocio, --18 286 | ttp.cd_contraparte, -- 19.cd_contraparte, --19 287 | ttp.dg_negocio, -- 20.dg_negocio, --20 288 | ttp.tp_neg, -- 21.tp_neg, --21 289 | ttp.qt_executada, -- 22.qt_executada, --22 290 | ttp.dc_observ, -- 23.dc_observ, --23 291 | ttp.dc_justif, -- 24.dc_justif, --24 292 | ttp.dc_emitente, -- 25.dc_emitente, --25 293 | ttp.dc_operador, -- 26.dc_operador, --26 294 | ttp.dc_cli_qualif, -- 27.dc_cli_qualif, --27 295 | convert(smalldatetime,substring(ttp.dt_pregao,1,4) 296 | + substring(ttp.dt_pregao,6,2) 297 | + substring(ttp.dt_pregao,9,2)) as dt_pregao, -- 28.dt_pregao, --28 298 | ttp.dc_hr_neg, -- 29.dc_hr_neg, --29 299 | ttp.dc_obs, -- 30.dc_obs, --30 300 | ttp.dc_mercado, -- 31.dc_mercado, --31 301 | ttp.nm_empresa, -- 32.nm_empresa, --32 302 | ttp.dc_especie, -- 33.dc_especie, --33 303 | ttp.pr_exerc, -- 34.pr_exerc, --34 304 | case when convert(int,right(ttp.dt_venc,1))>= 2079 305 | then CONVERT(smalldatetime,'2079-06-06') else 306 | convert(smalldatetime,substring(ttp.dt_venc,1,4) 307 | + substring(ttp.dt_venc,6,2) 308 | + substring(ttp.dt_venc,9,2)) end as dt_venc, -- 35.dt_venc, --35 309 | ttp.cd_carga, -- 36.cd_carga --36 310 | ttp.cd_mercado, -- 37.cd_mercado, --37 311 | ttp.vl_fator_cotacao, -- 38.vl_fator_cotacao, --38 312 | ttp.id_daytrade -- 39.id_daytrade) --39 313 | from dbo.ttp_operacao_corretora ttp 314 | join dbo.tcl_cliente_detalhe_bolsa cdb 315 | on cdb.cd_cliente_bolsa = ttp.cd_bolsa 316 | join dbo.tcl_cliente cl 317 | on cl.cd_cliente = cdb.cd_cliente 318 | left join dbo.tbl_operacao_corretora op 319 | on ttp.cd_chave = op.cd_chave 320 | and ttp.nr_negocio = op.nr_negocio 321 | and convert(smalldatetime,substring(ttp.dt_pregao,1,4) 322 | + substring(ttp.dt_pregao,6,2) 323 | + substring(ttp.dt_pregao,9,2)) = op.dt_pregao 324 | where ttp.nr_negocio is not null and (op.cd_chave is null 325 | or op.nr_negocio is null 326 | or op.dt_pregao is null) 327 | 328 | --- Insert tbl_operacao_corretora_beechmark 329 | 330 | insert into tbl_operacao_corretora_benchmark 331 | (cd_chave, --01 332 | cd_cliente, --02 333 | dc_operacao, --03 334 | dt_ordem, --04 335 | cd_bolsa, --05 336 | dg_bolsa, --06 337 | tp_ordem, --07 338 | dt_validade, --08 339 | dt_hr_ordem, --09 340 | dc_bolsa, --10 341 | dc_pesvinc, --11 342 | qt_espec, --12 343 | vl_preco_papel, --13 344 | dc_assessor, --14 345 | dc_papel, --15 346 | nr_negocio, --16 347 | qt_negocio, --17 348 | vl_negocio, --18 349 | cd_contraparte, --19 350 | dg_negocio, --20 351 | tp_neg, --21 352 | qt_executada, --22 353 | dc_observ, --23 354 | dc_justif, --24 355 | dc_emitente, --25 356 | dc_operador, --26 357 | dc_cli_qualif, --27 358 | dt_pregao, --28 359 | dc_hr_neg, --29 360 | dc_obs, --30 361 | dc_mercado, --31 362 | nm_empresa, --32 363 | dc_especie, --33 364 | pr_exerc, --34 365 | dt_venc, --35 366 | cd_carga, --36 367 | cd_mercado, --37 368 | vl_fator_cotacao, --38 369 | id_daytrade, 370 | vl_benchmark) --39 371 | select distinct 372 | substring(ttp.cd_chave,1,21) as cd_chave, -- 01. cd_chave, --01 373 | cl.cd_cliente, -- 02. cd_cliente, --02 374 | ttp.dc_operacao, -- 03. dc_operacao, --03 375 | convert(smalldatetime,substring(ttp.dt_ordem,1,4) 376 | + substring(ttp.dt_ordem,6,2) 377 | + substring(ttp.dt_ordem,9,2))as dt_ordem, -- 04.dt_ordem, --04 378 | ttp.cd_bolsa, -- 05.cd_bolsa, --05 379 | ttp.dg_bolsa, -- 06.dg_bolsa, --06 380 | ttp.tp_ordem, -- 07.tp_ordem, --07 381 | case when convert(int,right(ttp.dt_validade,1))>= 2079 382 | then CONVERT(smalldatetime,'2079-06-06') else 383 | convert(smalldatetime,substring(ttp.dt_validade,1,4) 384 | + substring(ttp.dt_validade,6,2) 385 | + substring(ttp.dt_validade,9,2)) end as dt_validade, -- 08.dt_validade, --08 386 | convert(smalldatetime,substring(ttp.dt_hr_ordem,1,4) 387 | + substring(ttp.dt_hr_ordem,6,2) + substring(ttp.dt_hr_ordem,9,2) 388 | + ' ' + substring(ttp.dt_hr_ordem,12,8)) as dt_hr_ordem, -- 09.dt_hr_ordem, --09 389 | ttp.dc_bolsa, -- 10.dc_bolsa, --10 390 | ttp.dc_pesvinc, -- 11.dc_pesvinc, --11 391 | ttp.qt_espec, -- 12.qt_espec, --12 392 | ttp.vl_preco_papel, -- 13.vl_preco_papel, --13 393 | ttp.dc_assessor, -- 14.dc_assessor, --14 394 | ttp.dc_papel, -- 15.dc_papel, --15 395 | ttp.nr_negocio, -- 16.nr_negocio, --16 396 | ttp.qt_negocio, -- 17.qt_negocio, --17 397 | ttp.vl_negocio, -- 18.vl_negocio, --18 398 | ttp.cd_contraparte, -- 19.cd_contraparte, --19 399 | ttp.dg_negocio, -- 20.dg_negocio, --20 400 | ttp.tp_neg, -- 21.tp_neg, --21 401 | ttp.qt_executada, -- 22.qt_executada, --22 402 | ttp.dc_observ, -- 23.dc_observ, --23 403 | ttp.dc_justif, -- 24.dc_justif, --24 404 | ttp.dc_emitente, -- 25.dc_emitente, --25 405 | ttp.dc_operador, -- 26.dc_operador, --26 406 | ttp.dc_cli_qualif, -- 27.dc_cli_qualif, --27 407 | convert(smalldatetime,substring(ttp.dt_pregao,1,4) 408 | + substring(ttp.dt_pregao,6,2) 409 | + substring(ttp.dt_pregao,9,2)) as dt_pregao, -- 28.dt_pregao, --28 410 | ttp.dc_hr_neg, -- 29.dc_hr_neg, --29 411 | ttp.dc_obs, -- 30.dc_obs, --30 412 | ttp.dc_mercado, -- 31.dc_mercado, --31 413 | ttp.nm_empresa, -- 32.nm_empresa, --32 414 | ttp.dc_especie, -- 33.dc_especie, --33 415 | ttp.pr_exerc, -- 34.pr_exerc, --34 416 | case when convert(int,right(ttp.dt_venc,1))>= 2079 417 | then CONVERT(smalldatetime,'2079-06-06') else 418 | convert(smalldatetime,substring(ttp.dt_venc,1,4) 419 | + substring(ttp.dt_venc,6,2) 420 | + substring(ttp.dt_venc,9,2)) end as dt_venc, -- 35.dt_venc, --35 421 | ttp.cd_carga, -- 36.cd_carga --36 422 | ttp.cd_mercado, -- 37.cd_mercado, --37 423 | ttp.vl_fator_cotacao, -- 38.vl_fator_cotacao, --38 424 | ttp.id_daytrade, -- 39.id_daytrade) --39 425 | ttp.vl_benchmark 426 | from dbo.ttp_operacao_corretora_benchmark ttp 427 | join dbo.tcl_cliente_detalhe_bolsa cdb 428 | on cdb.cd_cliente_bolsa = ttp.cd_bolsa 429 | join dbo.tcl_cliente cl 430 | on cl.cd_cliente = cdb.cd_cliente 431 | left join dbo.tbl_operacao_corretora_benchmark op 432 | on ttp.cd_chave = op.cd_chave 433 | and ttp.nr_negocio = op.nr_negocio 434 | and convert(smalldatetime,substring(ttp.dt_pregao,1,4) 435 | + substring(ttp.dt_pregao,6,2) 436 | + substring(ttp.dt_pregao,9,2)) = op.dt_pregao 437 | where ttp.nr_negocio is not null and (op.cd_chave is null 438 | or op.nr_negocio is null 439 | or op.dt_pregao is null) 440 | 441 | -- Recupera a qtde de registros inserido 442 | set @qt_regi_ins = @@rowcount; 443 | 444 | --Recupera a qtde de registros atualizado 445 | set @qt_regi_upd = 0; 446 | 447 | --Seta fim carga 448 | set @dt_termino = getdate(); 449 | 450 | --Finaliza controle de carga 451 | exec dbo.spgr_grava_log_carga 10, @cd_carga, 'Carga Operacao Corretora', @dt_termino, @dt_carga, @qt_regi_ins, @qt_regi_upd; 452 | 453 | end try 454 | begin catch 455 | 456 | exec dbo.spgr_tratar_erro; 457 | 458 | end catch 459 | GO 460 | 461 | 462 | -------------------------------------------------------------------------------- /02_Convert_Datas.sql: -------------------------------------------------------------------------------- 1 | 2 | select getdate() as datanormal, Convert(varchar(10),getdate(),103) as dataformatada103, 3 | Convert(varchar(25),getdate(),113) as dataformatada113, 4 | Convert(varchar(25),getdate(),22) as dataformatada22, 5 | Convert(varchar(25),getdate(),111) as dataformatada111, 6 | Convert(varchar(25),getdate(),130) as dataformatada130, 7 | Convert(varchar(25),getdate(),109) as dataformatada109, 8 | Convert(varchar(25),getdate(),120) as dataformatada120 9 | 10 | --- Teste passar de 103 para varchar 11 | --- E de varchar para 120 12 | 13 | select getdate() as datanormal,Convert(varchar(25),getdate(),103) as dataformatada103 14 | 15 | create table tb_teste_date 16 | (dt_teste varchar (15)) 17 | 18 | INSERT INTO [dbo].[tb_teste_date] 19 | ([dt_teste]) 20 | VALUES 21 | ('14/04/2021') 22 | GO 23 | 24 | update [dbo].[tb_teste_date] 25 | set dt_teste = '14/04/2021' 26 | 27 | --- Converte o formato de 14/04/2021 para 2021-04-14 00:00:00 28 | 29 | select 30 | convert(smalldatetime,substring(dt_teste,7,4)+ substring(dt_teste,4,2) 31 | + substring(dt_teste,1,2))as dt_ordem 32 | from tb_teste_date 33 | 34 | --- Converte o formato de 14042021 para 2021-04-14 00:00:00 35 | 36 | select 37 | convert(smalldatetime,substring(dt_teste,5,4)+ substring(dt_teste,3,2) 38 | + substring(dt_teste,1,2))as dt_ordem 39 | from tb_teste_date 40 | 41 | --- Converte o formato de 20210414 para 2021-04-14 00:00:00 42 | 43 | select 44 | convert(smalldatetime,substring(dt_teste,1,4)+ substring(dt_teste,5,2) 45 | + substring(dt_teste,7,2))as dt_ordem 46 | from tb_teste_date 47 | 48 | update [dbo].[tb_teste_date] 49 | set dt_teste = '14042021' 50 | 51 | --- Declarando variavel e utilizando conversão de data no where 52 | 53 | declare @dt_inicio smalldatetime = '2021-04-14' 54 | 55 | select @dt_inicio 56 | 57 | select dt_teste from tb_teste_date 58 | where convert(smalldatetime,substring(dt_teste,7,4)+ substring(dt_teste,4,2) 59 | + substring(dt_teste,1,2))= @dt_inicio 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /02_Views/01_Create_View.sql: -------------------------------------------------------------------------------- 1 | 2 | if exists(select * from sys.all_objects where name = 'VW_TPINVESTIDOR') 3 | Drop view VW_TPINVESTIDOR 4 | GO 5 | 6 | CREATE VIEW [dbo].[VW_TPINVESTIDOR] ("TIPO_INVEST", "DES_INVEST") AS 7 | SELECT cd_tipo_invest AS TIPO_INVEST, 8 | dc_tipo_invest AS DES_INVEST 9 | FROM dbo.tb_vw_corretora_tipo_investidor; 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /02_Views/Views: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /03_Processos_Ativos.sql: -------------------------------------------------------------------------------- 1 | 2 | SELECT 3 | Processo = spid 4 | ,Computador = hostname 5 | ,Usuario = loginame 6 | ,Status = status 7 | ,BloqueadoPor = blocked 8 | ,TipoComando = cmd 9 | ,Aplicativo = program_name 10 | FROM 11 | master..sysprocesses 12 | WHERE 13 | status in ('runnable', 'suspended') 14 | ORDER BY 15 | blocked desc, status, spid 16 | -------------------------------------------------------------------------------- /04_Tempo_Entre_DatasHoras.sql: -------------------------------------------------------------------------------- 1 | -- Defina suas duas datas 2 | DECLARE @dataInicial DATETIME = '2022-01-01'; 3 | DECLARE @dataFinal DATETIME = '2023-01-01'; 4 | 5 | -- Calcule a diferença em dias 6 | DECLARE @diasPassados INT; 7 | SET @diasPassados = DATEDIFF(DAY, @dataInicial, @dataFinal); 8 | 9 | -- Calcule a diferença em horas, minutos e segundos 10 | DECLARE @horasPassadas INT, @minutosPassados INT, @segundosPassados INT; 11 | SET @horasPassadas = DATEDIFF(HOUR, @dataInicial, @dataFinal); 12 | SET @minutosPassados = DATEDIFF(MINUTE, @dataInicial, @dataFinal); 13 | SET @segundosPassados = DATEDIFF(SECOND, @dataInicial, @dataFinal); 14 | 15 | -- Exiba os resultados 16 | PRINT 'Passaram-se ' + CAST(@diasPassados AS VARCHAR) + ' dias.'; 17 | PRINT 'Passaram-se ' + CAST(@horasPassadas AS VARCHAR) + ' horas.'; 18 | PRINT 'Passaram-se ' + CAST(@minutosPassados AS VARCHAR) + ' minutos.'; 19 | PRINT 'Passaram-se ' + CAST(@segundosPassados AS VARCHAR) + ' segundos.'; 20 | -------------------------------------------------------------------------------- /Functions/06_Functions_Replace.sql: -------------------------------------------------------------------------------- 1 | update dbo.tgr_lista_Pep 2 | set documentos = (REPLACE(REPLACE(REPLACE([documentos],'.', ''),'-', ''),'/', '')) 3 | -------------------------------------------------------------------------------- /Functions/09_Function_DiaUtil.sql: -------------------------------------------------------------------------------- 1 |  2 | 3 | ALTER function [dbo].[fncDia_Util_Anterior]( @dt_dia smalldatetime, @dias_uteis int ) 4 | returns smalldatetime 5 | as 6 | begin 7 | declare @contador int 8 | set @contador = 1 9 | 10 | --set @dt_dia = dateadd(day, -1, @dt_dia) 11 | 12 | while (@contador <= @dias_uteis) 13 | begin 14 | 15 | if exists (select top 1 cd_feriado from dbo.tgr_feriados with (nolock) 16 | where dt_feriado = dateadd(day, -1, @dt_dia)) 17 | or (datepart(weekday, dateadd(day, -1, @dt_dia)) in (7, 1)) 18 | begin 19 | set @dt_dia = dateadd(day, -1, @dt_dia) 20 | 21 | set @contador = @contador - 1 22 | 23 | end 24 | else 25 | begin 26 | 27 | set @dt_dia = dateadd(day, -1, @dt_dia) 28 | end 29 | 30 | set @contador = @contador + 1 31 | end 32 | 33 | return @dt_dia 34 | 35 | end 36 | -------------------------------------------------------------------------------- /Functions/1: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Grants/01_Grants_Users.sql: -------------------------------------------------------------------------------- 1 | 2 | EXEC SP_SRVROLEPERMISSION 'bulkadmin' 3 | 4 | -- Criação de um banco para nossos testes 5 | CREATE DATABASE RoleTest 6 | GO 7 | 8 | USE RoleTest 9 | GO 10 | 11 | --Tabela pra teste 12 | 13 | CREATE TABLE dbo.Roles( 14 | linha INT NULL, 15 | nome VARCHAR(20) NULL, 16 | descricao VARCHAR(100) NULL) 17 | 18 | select * from dbo.Roles 19 | 20 | -- Criação dos logins para teste 21 | USE MASTER 22 | GO 23 | -- Esse cara foi eleito BulkAdmin pela comissão oficial dos databases do brasil 24 | CREATE LOGIN CarinhaBulkAdmin WITH PASSWORD = 'bulkadmin1', CHECK_POLICY = OFF; 25 | 26 | -- Adiciona o login à role Bulkadmin 27 | EXEC sp_addsrvrolemember 'CarinhaBulkAdmin', 'bulkadmin'; 28 | 29 | --Esse cara terá permissão de inserção e nada mais (nem arquivo externo) 30 | CREATE LOGIN CarinhaDoInsert WITH PASSWORD = 'insert1', CHECK_POLICY = OFF; 31 | 32 | /* Criando usuários para ambos os logins na base */ 33 | 34 | USE RoleTest 35 | 36 | EXEC sp_addsrvrolemember CarinhaDoInsert, 'bulkadmin' 37 | 38 | --O usuário foi criado. Lembrando: ele tem role de servidor Bulkadmin 39 | CREATE USER usrBulkInsert FOR LOGIN CarinhaBulkAdmin 40 | 41 | -- O usuário que só pode inserir e não pode fazer bulk insert 42 | CREATE USER usrInsert FOR LOGIN CarinhaDoInsert 43 | 44 | -- Ou seja...O único que tem permissão de Insert é o usrInsert 45 | GRANT INSERT ON Object::dbo.Roles TO usrInsert 46 | 47 | GRANT select ON Object::dbo.Roles TO usrBulkInsert 48 | 49 | --- Logando com o carinha 50 | 51 | USE RoleTest 52 | GO 53 | -- Insert deve funcionar normalmente. 54 | INSERT INTO dbo.Roles (linha,nome,descricao) VALUES (0,'bulkadm','Começo de teste') 55 | -- Agora tente dar um BULK INSERT sem ter permissão... 56 | BULK INSERT dbo.Roles 57 | FROM 'C:\temp\carga.txt' WITH (FIELDTERMINATOR = ',', 58 | ROWTERMINATOR = 'n') 59 | 60 | select * from dbo.Roles 61 | -------------------------------------------------------------------------------- /Grants/Grants: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Procedures/03_Consulta_Conteudos_Procedures.sql: -------------------------------------------------------------------------------- 1 | 2 | SELECT 3 | OBJECT_NAME(m.object_id) AS ProcedureName, 4 | m.definition AS ProcedureDefinition 5 | FROM 6 | sys.sql_modules m 7 | INNER JOIN sys.objects o ON m.object_id = o.object_id 8 | WHERE 9 | o.type = 'P' AND 10 | m.definition like '%qtd_dias%'; 11 | 12 | select * from tsv_envio_email 13 | 14 | sp_helptext spsv_processar_integracao_ad 15 | 16 | 17 | -------------------------------------------------------------------------------- /Procedures/05_Create_Procedure.sql: -------------------------------------------------------------------------------- 1 | 2 | if exists(select name from sys.procedures where name = 'spcb_valores_elevados') 3 | drop procedure spcb_valores_elevados; 4 | go 5 | 6 | SET ANSI_NULLS ON 7 | GO 8 | SET QUOTED_IDENTIFIER ON 9 | GO 10 | CREATE procedure [dbo].[spcb_valores_elevados] 11 | @cd_execucao int, 12 | @cd_cliente dt_cd_cliente, 13 | @cd_produto smallint, 14 | @cd_enquadramento smallint, 15 | @cd_unico smallint, 16 | @ttp_varredura_mov_1 dtt_mov_varredura readonly, 17 | @ttp_varredura_mov_2 dtt_mov_varredura readonly, 18 | @ttp_varredura_mov_3 dtt_mov_varredura readonly, 19 | @dt_inicio smalldatetime, 20 | @dt_final smalldatetime, 21 | @vl_parametro_1 float = null, 22 | @vl_parametro_2 float = null, 23 | @vl_parametro_3 float = null, 24 | @vl_parametro_4 float = null, 25 | @vl_parametro_5 float = null, 26 | @vl_parametro_6 float = null, 27 | @vl_parametro_7 float = null, 28 | @vl_parametro_8 float = null, 29 | @vl_parametro_9 float = null, 30 | @vl_parametro_10 float = null, 31 | @vl_parametro_11 float = null, 32 | @vl_parametro_12 float = null, 33 | @vl_parametro_13 float = null, 34 | @vl_parametro_14 float = null, 35 | @vl_parametro_15 float = null, 36 | @vl_parametro_16 float = null, 37 | @vl_parametro_17 float = null, 38 | @vl_parametro_18 float = null, 39 | @vl_parametro_19 float = null, 40 | @vl_parametro_20 float = null, 41 | @vl_parametro_21 float = null, 42 | @vl_parametro_22 float = null, 43 | @vl_parametro_23 float = null, 44 | @vl_parametro_24 float = null, 45 | @vl_parametro_25 float = null, 46 | @vl_parametro_26 float = null, 47 | @vl_parametro_27 float = null, 48 | @vl_parametro_28 float = null, 49 | @vl_parametro_29 float = null, 50 | @vl_parametro_30 float = null 51 | as 52 | begin try; 53 | 54 | --- 01. Declara as variaveis necessárias para a varredura 55 | 56 | declare @qtde_transacoes int 57 | declare @vl_movimentacao money 58 | declare @tp_pessoa varchar (1) 59 | declare @vl_cap_finan_anual float 60 | declare @vl_percentual float; 61 | declare @vl_percentual_acima float; 62 | 63 | --- 02. Capturar tipo pessoa através do Código do Cliente. 64 | 65 | select @tp_pessoa = tp_pessoa from dbo.tcl_cliente where cd_cliente = @cd_cliente 66 | 67 | --- 03. Capturando a tabela temporaria para verificar as movimentações 68 | 69 | declare @ttp_transacao_cliente as table 70 | (cd_transacao varchar(20), 71 | tp_transacao varchar(1) null, 72 | nm_contraparte varchar(200) null, 73 | cd_natureza_operacao varchar(20) null, 74 | vl_valor_real money null, 75 | cd_boleto int null); 76 | 77 | --- 04. Insert das movimentações do Cliente na Tabela Temporaria 78 | 79 | insert into @ttp_transacao_cliente 80 | (cd_transacao, 81 | tp_transacao, 82 | nm_contraparte, 83 | cd_natureza_operacao, 84 | vl_valor_real, 85 | cd_boleto) 86 | select distinct dc_registro as cd_transacao, 87 | dc_registro1 as tp_transacao, 88 | dc_registro2 as nm_contraparte, 89 | dc_registro5 as cd_natureza_operacao, 90 | vl_registro as vl_valor_real, 91 | dc_registro6 as cd_boleto 92 | from @ttp_varredura_mov_1 93 | where cd_cliente = @cd_cliente 94 | 95 | --- 05. Verifica a quantidade de Transação, Valor Total Movimentado 96 | 97 | set @qtde_transacoes = (select isnull(count(distinct cd_transacao),0) from @ttp_transacao_cliente) 98 | set @vl_movimentacao = (select isnull(sum(vl_valor_real),0) from @ttp_transacao_cliente) 99 | 100 | --- 06. Se pessoal fisica e Valor Total Movimentado superior ao 'Parametro 1', 101 | --- então o alerta é gerado 102 | if (@tp_pessoa = 'F') 103 | Begin 104 | 105 | if (@vl_movimentacao >= @vl_parametro_1) 106 | begin 107 | 108 | if not exists( 109 | select 1 110 | from dbo.tpr_varredura_alertas tva with(nolock) 111 | where @qtde_transacoes = tva.dc_alerta 112 | and @vl_movimentacao = vl_alerta 113 | and tva.cd_enquadramento = @cd_enquadramento 114 | and tva.cd_produto = @cd_produto 115 | and tva.cd_cliente = @cd_cliente 116 | and tva.dt_movimentacao = @dt_inicio) 117 | 118 | begin 119 | 120 | insert into dbo.tpr_varredura_alertas 121 | (cd_produto, 122 | cd_execucao, 123 | cd_enquadramento, 124 | cd_cliente, 125 | dt_movimentacao, 126 | cd_unico, 127 | dc_alerta, 128 | vl_alerta) 129 | select distinct 130 | @cd_produto, 131 | @cd_execucao, 132 | @cd_enquadramento, 133 | @cd_cliente, 134 | @dt_inicio, 135 | @cd_unico, 136 | @qtde_transacoes, 137 | @vl_movimentacao; 138 | 139 | insert into dbo.tpr_varredura_alertas_movimentacao 140 | (cd_produto, 141 | cd_execucao, 142 | cd_alerta_varr, 143 | cd_movimentacao 144 | ) 145 | select 146 | @cd_produto, 147 | @cd_execucao, 148 | cd_alerta_varr, 149 | cd_transacao 150 | from dbo.tpr_varredura_alertas tva with(nolock) 151 | join @ttp_transacao_cliente ttp on 152 | @qtde_transacoes = tva.dc_alerta 153 | and @vl_movimentacao = vl_alerta 154 | and tva.cd_enquadramento = @cd_enquadramento 155 | and tva.cd_produto = @cd_produto 156 | and tva.cd_cliente = @cd_cliente 157 | and tva.dt_movimentacao = @dt_inicio 158 | 159 | end 160 | end 161 | end 162 | -- 07. Se Pessoa Juridica,e valor total movimentado superior ao parametro2, 163 | -- então é verificada a capacidade Financeira 164 | else 165 | if (@tp_pessoa = 'J') 166 | Begin 167 | if (@vl_movimentacao >= @vl_parametro_2) 168 | begin 169 | --- Verificando a capacidade financeira do Cliente apenas se Pessoa Jurídica e valor Maior que Parametro2 170 | 171 | select @vl_cap_finan_anual = case when isnull (vl_cap_finan_anual,0) = 0 172 | then 75000.00 else vl_cap_finan_anual end 173 | from dbo.tcl_cliente_detalhe_generico 174 | where cd_cliente = @cd_cliente 175 | 176 | --- 08. Verifica percentual da Capacidade Financeira 177 | Set @vl_percentual = ((@vl_cap_finan_anual * @vl_parametro_3) / 100) 178 | 179 | --- 09. Se valor Movimentado for maior ou igual a 10% 'Parametro3', então o alerta é gerado. 180 | 181 | If (@vl_movimentacao >= @vl_percentual) 182 | Begin 183 | if not exists( 184 | select 1 185 | from dbo.tpr_varredura_alertas tva with(nolock) 186 | where @qtde_transacoes = tva.dc_alerta 187 | and @vl_movimentacao = vl_alerta 188 | and tva.cd_enquadramento = @cd_enquadramento 189 | and tva.cd_produto = @cd_produto 190 | and tva.cd_cliente = @cd_cliente 191 | and tva.dt_movimentacao = @dt_inicio) 192 | 193 | begin 194 | 195 | insert into dbo.tpr_varredura_alertas 196 | (cd_produto, 197 | cd_execucao, 198 | cd_enquadramento, 199 | cd_cliente, 200 | dt_movimentacao, 201 | cd_unico, 202 | dc_alerta, 203 | vl_alerta) 204 | select distinct 205 | @cd_produto, 206 | @cd_execucao, 207 | @cd_enquadramento, 208 | @cd_cliente, 209 | @dt_inicio, 210 | @cd_unico, 211 | @qtde_transacoes, 212 | @vl_movimentacao; 213 | 214 | insert into dbo.tpr_varredura_alertas_movimentacao 215 | (cd_produto, 216 | cd_execucao, 217 | cd_alerta_varr, 218 | cd_movimentacao 219 | ) 220 | select 221 | @cd_produto, 222 | @cd_execucao, 223 | cd_alerta_varr, 224 | cd_transacao 225 | from dbo.tpr_varredura_alertas tva with(nolock) 226 | join @ttp_transacao_cliente ttp on 227 | @qtde_transacoes = tva.dc_alerta 228 | and @vl_movimentacao = vl_alerta 229 | and tva.cd_enquadramento = @cd_enquadramento 230 | and tva.cd_produto = @cd_produto 231 | and tva.cd_cliente = @cd_cliente 232 | and tva.dt_movimentacao = @dt_inicio 233 | 234 | end 235 | 236 | end 237 | 238 | end 239 | 240 | end 241 | 242 | end try 243 | begin catch 244 | exec dbo.spgr_tratar_erro; 245 | end catch 246 | -------------------------------------------------------------------------------- /Procedures/07_Procedure_Cursor.txt: -------------------------------------------------------------------------------- 1 | use SIRCOI 2 | go 3 | 4 | 5 | ALTER procedure [dbo].[spgr_varredura] 6 | @id_todos_clientes bit, 7 | @cd_cliente dt_cd_cliente, 8 | @id_grupo_econ bit, 9 | @id_relacionamento bit, 10 | @cd_produto int, 11 | @dt_inicio smalldatetime, 12 | @dt_final smalldatetime, 13 | @id_automatica bit, 14 | @id_mensal bit = 0, 15 | @cd_usuario int = null, 16 | @id_resumir bit = 0 17 | 18 | as 19 | begin try 20 | set dateformat mdy; 21 | 22 | --Variaveis 23 | 24 | declare @cd_varredura_aut int; 25 | declare @vl_total_mov float; 26 | declare @cd_cliente_int dt_cd_cliente; 27 | declare @cd_produto_int int; 28 | declare @cd_enquadramento smallint; 29 | declare @nm_stored_proc varchar(50); 30 | declare @dc_execucao_sp varchar(300); 31 | declare @dt_inicio_varredura datetime; 32 | declare @hr_ultimo_cliente datetime; 33 | declare @vl_contador_total int; 34 | declare @tp_carga tinyint; 35 | declare @cd_produto_resumir int; 36 | declare @cd_cliente_resumir dt_cd_cliente; 37 | 38 | -- Criar tabela temporaria para movimentação Corretora 39 | 40 | if object_id('tempdb..##ttp_movto') is not null 41 | drop table ##ttp_movto; 42 | 43 | -- cria temp para movimentacao 44 | create table ##ttp_movto 45 | (cd_cliente int null, 46 | cd_ativo varchar(20) null, --collate SQL_Latin1_General_CP1_CI_AS null, 47 | cd_mercado varchar(3) null, -- collate SQL_Latin1_General_CP1_CI_AS null, 48 | dc_mercado varchar(30) null, --collate SQL_Latin1_General_CP1_CI_AS null, 49 | cd_contraparte varchar(6) null, -- collate SQL_Latin1_General_CP1_CI_AS null, 50 | nr_ordem bigint null, 51 | nr_negocio numeric(12) null, 52 | tp_negocio char(2) null, -- collate SQL_Latin1_General_CP1_CI_AS null, 53 | tp_operacao char(1) null, -- collate SQL_Latin1_General_CP1_CI_AS null, 54 | vl_total money null, 55 | qt_negocio numeric(15) null, 56 | vl_negocio money null, 57 | hr_negocio time null, 58 | id_daytrade bit null) 59 | 60 | --Cria tabela temp 61 | 62 | create table #ttp_cliente( 63 | cd_cliente int 64 | ); 65 | 66 | if (@id_resumir = 1) 67 | begin 68 | 69 | set @id_automatica = 1; 70 | set @id_todos_clientes = 1; 71 | set @cd_cliente = ''; 72 | set @id_grupo_econ = 0; 73 | set @id_relacionamento = 0; 74 | set @cd_usuario = null; 75 | 76 | end 77 | 78 | if (@cd_produto = 0) 79 | 80 | begin 81 | 82 | declare cr_produtos cursor 83 | for 84 | select cd_produto 85 | from dbo.tpr_produtos_varredura; 86 | 87 | end 88 | else 89 | begin 90 | declare cr_produtos cursor 91 | for 92 | select cd_produto 93 | from dbo.tpr_produtos_varredura 94 | where cd_produto = @cd_produto; 95 | 96 | end 97 | 98 | open cr_produtos 99 | fetch next from cr_produtos into @cd_produto_int 100 | 101 | --Cursor Produtos 102 | 103 | while @@fetch_status = 0 104 | begin 105 | 106 | if ((@id_resumir = 1) and (@id_automatica = 1) and (@id_todos_clientes = 1)) 107 | begin 108 | 109 | select top 1 110 | 111 | @cd_varredura_aut = cd_varredura_aut, 112 | @dt_inicio_varredura = dt_inicio, 113 | @cd_produto_resumir = cd_produto, 114 | @cd_cliente_resumir = cd_atual, 115 | @tp_carga = tp_carga, 116 | @dt_inicio = dt_carr_inicio, 117 | @dt_final = dt_carr_final 118 | from dbo.tsv_status_varredura with (nolock) 119 | 120 | where id_terminado = 0 121 | order by dt_inicio desc 122 | 123 | set @hr_ultimo_cliente = @dt_inicio_varredura 124 | if @tp_carga = 1 125 | set @id_mensal = 0 126 | else 127 | if @tp_carga = 2 128 | set @id_mensal = 1 129 | 130 | if convert(int, @cd_cliente_resumir) > 0 131 | while @cd_produto_int <> @cd_produto_resumir 132 | fetch next from cr_produtos into @cd_produto_int 133 | 134 | end 135 | 136 | if ((@id_resumir = 0) and (@id_automatica = 1) and (@id_todos_clientes = 1)) 137 | begin 138 | 139 | set @dt_inicio_varredura = getdate() 140 | set @hr_ultimo_cliente = @dt_inicio_varredura 141 | if @id_mensal = 0 142 | set @tp_carga = 1 143 | else 144 | if @id_mensal = 1 145 | set @tp_carga = 2 146 | 147 | insert into dbo.tsv_status_varredura (dt_inicio, tp_carga, cd_atual, cd_produto, dt_carr_inicio, dt_carr_final, vl_contador_atual, vl_contador_total, vl_tempo_carga_cliente, id_terminado) 148 | values(@dt_inicio_varredura, @tp_carga, '0', @cd_produto_int, @dt_inicio, @dt_final, 0, 0, '00:00', 0); 149 | set @cd_varredura_aut = scope_identity(); 150 | 151 | end 152 | 153 | if (@cd_produto_int = 1) --Clientes 154 | begin 155 | 156 | if (@id_todos_clientes = 1) 157 | 158 | begin 159 | 160 | --Alertas coligados 161 | 162 | exec dbo.spgr_grava_alertas_coligados @dt_inicio, @dt_final, @cd_produto, @id_mensal 163 | 164 | insert into #ttp_cliente (cd_cliente) 165 | select tcl.cd_cliente -- Verificar 166 | from dbo.tcl_cliente tcl with (nolock) 167 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on tcl.cd_cliente = cdg.cd_cliente --Verificar 168 | where ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 169 | union 170 | select tcl.cd_cliente -- Incluindo na analise os clientes corretora 171 | from dbo.tcl_cliente tcl with (nolock) 172 | join dbo.tcl_cliente_detalhe_bolsa cdg with (nolock) on tcl.cd_cliente = cdg.cd_cliente --Incluindo na analise os clientes corretora 173 | 174 | set @vl_contador_total = @@rowcount; 175 | 176 | end 177 | else 178 | begin 179 | 180 | insert into #ttp_cliente( cd_cliente ) 181 | values(@cd_cliente); 182 | 183 | end 184 | 185 | end 186 | else 187 | 188 | if (@cd_produto_int = 2) --Conta Corrente 189 | 190 | begin 191 | 192 | if (@id_todos_clientes = 1) --Todos os Clientes 193 | 194 | begin 195 | 196 | if (@id_mensal = 0) --Diária 197 | begin 198 | 199 | insert into #ttp_cliente (cd_cliente) 200 | select distinct ccc.cd_cliente 201 | from dbo.tcc_mov_conta_corr mcc with (nolock) 202 | join dbo.tcc_cliente_conta_corr ccc with (nolock) on mcc.cd_agencia = ccc.cd_agencia 203 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on ccc.cd_cliente = cdg.cd_cliente --Verificar 204 | and mcc.nm_conta_corr = ccc.nm_conta_corr 205 | join dbo.tgr_cargas grc with (nolock) on mcc.cd_carga = grc.cd_carga 206 | and grc.cd_produto = 2 207 | and grc.id_termino = 1 208 | and left(rtrim(ltrim(grc.nm_arquivo)), 9) = 'CONTA_MOV' 209 | where grc.dt_referencia between @dt_inicio and @dt_final 210 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 211 | 212 | 213 | set @vl_contador_total = @@rowcount; 214 | 215 | end 216 | else --Mensal 217 | begin 218 | 219 | insert into #ttp_cliente (cd_cliente) 220 | select distinct ccc.cd_cliente 221 | from dbo.tcc_mov_conta_corr mcc with (nolock) 222 | join dbo.tcc_cliente_conta_corr ccc with (nolock) on mcc.cd_agencia = ccc.cd_agencia 223 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on ccc.cd_cliente = cdg.cd_cliente --Verificar 224 | and mcc.nm_conta_corr = ccc.nm_conta_corr 225 | where mcc.dt_movimentacao between @dt_inicio and @dt_final 226 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 227 | 228 | set @vl_contador_total = @@rowcount; 229 | 230 | end 231 | 232 | end 233 | else 234 | begin 235 | 236 | insert into #ttp_cliente( cd_cliente ) 237 | values(@cd_cliente); 238 | 239 | end 240 | 241 | end 242 | else 243 | if (@cd_produto_int = 3) --Câmbio 244 | begin 245 | 246 | if (@id_todos_clientes = 1) --Todos os Clientes 247 | 248 | begin 249 | 250 | if (@id_mensal = 0) --Diária 251 | begin 252 | 253 | insert into #ttp_cliente (cd_cliente) 254 | select distinct ctr.cd_cliente 255 | from dbo.tcb_contrato ctr with (nolock) 256 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on ctr.cd_cliente = cdg.cd_cliente --Verificar 257 | join dbo.tcb_contrato_evento cte with (nolock) on ctr.cd_contrato = cte.cd_contrato 258 | join dbo.tgr_cargas grc with (nolock) on cte.cd_carga = grc.cd_carga 259 | and grc.cd_produto = 3 260 | and grc.id_termino = 1 261 | and left(rtrim(ltrim(grc.nm_arquivo)), 13) = 'CAMBIO_EVENTO' 262 | where grc.dt_referencia between @dt_inicio and @dt_final 263 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 264 | 265 | set @vl_contador_total = @@rowcount; 266 | 267 | end 268 | else 269 | begin 270 | 271 | --Alertas coligados 272 | 273 | exec dbo.spgr_grava_alertas_coligados @dt_inicio, @dt_final, @cd_produto, @id_mensal 274 | 275 | insert into #ttp_cliente (cd_cliente) 276 | select distinct ctr.cd_cliente 277 | from dbo.tcb_contrato ctr with (nolock) 278 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on ctr.cd_cliente = cdg.cd_cliente --Verificar 279 | join dbo.tcb_contrato_evento cte with (nolock) on ctr.cd_contrato = cte.cd_contrato 280 | where cte.dt_operacao between @dt_inicio and @dt_final 281 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE'--Verificar 282 | 283 | set @vl_contador_total = @@rowcount; 284 | 285 | end 286 | end 287 | else 288 | begin 289 | 290 | insert into #ttp_cliente( cd_cliente ) 291 | values(@cd_cliente); 292 | 293 | end 294 | 295 | end 296 | else 297 | if (@cd_produto_int = 4) --Renda Fixa 298 | begin 299 | 300 | if (@id_todos_clientes = 1) --Todos os Clientes 301 | 302 | begin 303 | 304 | if (@id_mensal = 0) --Diária 305 | 306 | begin 307 | 308 | insert into #ttp_cliente (cd_cliente) 309 | select distinct rfo.cd_cliente 310 | from dbo.trf_operacao rfo with (nolock) 311 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on rfo.cd_cliente = cdg.cd_cliente --Verificar 312 | join dbo.tgr_cargas grc with (nolock) on rfo.cd_carga = grc.cd_carga 313 | and grc.cd_produto = 4 314 | and grc.id_termino = 1 315 | and left(rtrim(ltrim(grc.nm_arquivo)), 10) = 'RENDA_FIXA' 316 | where grc.dt_referencia between @dt_inicio and @dt_final 317 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 318 | 319 | set @vl_contador_total = @@rowcount; 320 | 321 | end 322 | else --Mensal 323 | begin 324 | 325 | set @vl_contador_total = 0 326 | 327 | end 328 | 329 | end 330 | else 331 | begin 332 | 333 | insert into #ttp_cliente( cd_cliente ) 334 | values(@cd_cliente); 335 | 336 | end 337 | 338 | end 339 | 340 | else 341 | 342 | if (@cd_produto_int = 5) --Swap 343 | 344 | begin 345 | 346 | if (@id_todos_clientes = 1) --Todos os Clientes 347 | begin 348 | 349 | if (@id_mensal = 0) --Diária 350 | begin 351 | 352 | insert into #ttp_cliente (cd_cliente) 353 | select distinct swo.cd_cliente 354 | from dbo.tsw_operacao swo with (nolock) 355 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on swo.cd_cliente = cdg.cd_cliente --Verificar 356 | join dbo.tgr_cargas grc with (nolock) on swo.cd_carga = grc.cd_carga 357 | and grc.cd_produto = 5 358 | and grc.id_termino = 1 359 | and left(rtrim(ltrim(grc.nm_arquivo)), 4) = 'SWAP' 360 | where grc.dt_referencia between @dt_inicio and @dt_final 361 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 362 | 363 | set @vl_contador_total = @@rowcount; 364 | 365 | end 366 | else --Mensal 367 | begin 368 | 369 | set @vl_contador_total = 0 370 | 371 | end 372 | 373 | end 374 | 375 | else 376 | 377 | begin 378 | 379 | insert into #ttp_cliente( cd_cliente ) 380 | values(@cd_cliente); 381 | 382 | end 383 | 384 | end 385 | 386 | else 387 | 388 | if (@cd_produto_int = 6) --Empréstimos 389 | 390 | begin 391 | 392 | if (@id_todos_clientes = 1) --Todos os Clientes 393 | begin 394 | 395 | if (@id_mensal = 0) --Diária 396 | begin 397 | 398 | insert into #ttp_cliente (cd_cliente) 399 | select distinct epo.cd_cliente 400 | from dbo.tep_contrato epo with (nolock) 401 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on epo.cd_cliente = cdg.cd_cliente --Verificar 402 | join dbo.tgr_cargas grc with (nolock) on epo.cd_carga = grc.cd_carga 403 | and grc.cd_produto = 6 404 | and grc.id_termino = 1 405 | and left(rtrim(ltrim(grc.nm_arquivo)), 11) = 'EMPRESTIMOS' 406 | where grc.dt_referencia between @dt_inicio and @dt_final 407 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 408 | 409 | set @vl_contador_total = @@rowcount; 410 | end 411 | else 412 | 413 | if (@id_mensal = 1) --Mensal 414 | 415 | begin 416 | 417 | insert into #ttp_cliente (cd_cliente) 418 | select distinct tpc.cd_cliente 419 | from dbo.tep_contrato tpc with (nolock) 420 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on tpc.cd_cliente = cdg.cd_cliente --Verificar 421 | where tpc.dt_operacao between @dt_inicio and @dt_final 422 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 423 | 424 | set @vl_contador_total = @@rowcount; 425 | 426 | end 427 | 428 | end 429 | else 430 | begin 431 | 432 | insert into #ttp_cliente( cd_cliente ) 433 | values(@cd_cliente); 434 | 435 | end 436 | 437 | end 438 | 439 | else 440 | 441 | if (@cd_produto_int = 7) --Linha de Crédito 442 | begin 443 | 444 | if (@id_todos_clientes = 1) --Todos os Clientes 445 | begin 446 | 447 | if (@id_mensal = 0) --Diária 448 | begin 449 | 450 | insert into #ttp_cliente (cd_cliente) 451 | select distinct ctr.cd_cliente 452 | from dbo.tlc_contrato ctr with (nolock) 453 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on ctr.cd_cliente = cdg.cd_cliente --Verificar 454 | join dbo.tlc_contrato_evento cte with (nolock) on ctr.cd_filial = cte.cd_filial 455 | and ctr.cd_contrato = cte.cd_contrato 456 | and ctr.tp_contrato = cte.tp_contrato 457 | join dbo.tgr_cargas grc with (nolock) on cte.cd_carga = grc.cd_carga 458 | and grc.cd_produto = 7 459 | and grc.id_termino = 1 460 | and left(rtrim(ltrim(grc.nm_arquivo)), 16) = 'LINHA_CREDITO_EV' 461 | where grc.dt_referencia between @dt_inicio and @dt_final 462 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 463 | 464 | set @vl_contador_total = @@rowcount; 465 | 466 | end 467 | else 468 | begin 469 | 470 | --Alertas coligados 471 | 472 | exec dbo.spgr_grava_alertas_coligados @dt_inicio, @dt_final, @cd_produto, @id_mensal 473 | 474 | insert into #ttp_cliente (cd_cliente) 475 | select distinct ctr.cd_cliente 476 | from dbo.tlc_contrato ctr with (nolock) 477 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on ctr.cd_cliente = cdg.cd_cliente --Verificar 478 | join dbo.tlc_contrato_evento cte with (nolock) on ctr.cd_filial = cte.cd_filial 479 | and ctr.cd_contrato = cte.cd_contrato 480 | and ctr.tp_contrato = cte.tp_contrato 481 | where cte.dt_operacao between @dt_inicio and @dt_final 482 | and ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 483 | union 484 | select tcl.cd_cliente -- Incluindo na analise os clientes corretora 485 | from dbo.tcl_cliente tcl with (nolock) 486 | join dbo.tcl_cliente_detalhe_bolsa cdg with (nolock) on tcl.cd_cliente = cdg.cd_cliente --Incluindo na analise os clientes corretora 487 | 488 | set @vl_contador_total = @@rowcount; 489 | 490 | end 491 | 492 | end 493 | else 494 | begin 495 | 496 | insert into #ttp_cliente( cd_cliente ) 497 | values(@cd_cliente); 498 | 499 | end 500 | 501 | end 502 | else 503 | 504 | if (@cd_produto_int = 8) --Consolidados 505 | 506 | begin 507 | 508 | if (@id_todos_clientes = 1) 509 | begin 510 | 511 | insert into #ttp_cliente (cd_cliente) 512 | select tcl.cd_cliente -- Verificar 513 | from dbo.tcl_cliente tcl with (nolock) 514 | join dbo.tcl_cliente_detalhe_generico cdg with (nolock) on tcl.cd_cliente = cdg.cd_cliente --Verificar 515 | where ltrim(rtrim(cdg.dc_status)) = 'ACTIVE' --Verificar 516 | 517 | set @vl_contador_total = @@rowcount; 518 | 519 | end 520 | else 521 | begin 522 | 523 | insert into #ttp_cliente( cd_cliente ) 524 | values(@cd_cliente); 525 | 526 | end 527 | 528 | end 529 | 530 | --- Começando o contador de corretora 531 | else 532 | if (@cd_produto_int = 9) --Corretora 533 | begin 534 | 535 | if (@id_todos_clientes = 1) 536 | begin 537 | 538 | if (@id_mensal = 0) --Diario 539 | begin 540 | 541 | insert into #ttp_cliente (cd_cliente) 542 | select distinct crm.cd_cliente 543 | from dbo.tbl_operacao_corretora crm with (nolock) 544 | join dbo.tgr_cargas gc with (nolock) 545 | on crm.cd_carga = gc.cd_carga 546 | and gc.cd_produto = 10 547 | where gc.dt_referencia between @dt_inicio and @dt_final 548 | union 549 | --- Incluir todas masters - ALF 550 | select distinct a.cd_cliente 551 | from dbo.tcl_cliente_detalhe_bolsa a 552 | where cd_cliente_bolsa = cd_master 553 | 554 | 555 | set @vl_contador_total = @@rowcount; 556 | 557 | insert into ##ttp_movto(cd_cliente, cd_ativo, cd_mercado, dc_mercado, cd_contraparte, nr_ordem, nr_negocio, tp_negocio, 558 | tp_operacao, vl_total, qt_negocio, vl_negocio, hr_negocio, id_daytrade) 559 | select distinct ope.cd_cliente, ope.dc_papel, ope.cd_mercado, ope.dc_mercado, ope.cd_contraparte, ope.cd_chave, 560 | ope.nr_negocio, ope.tp_neg, ope.dc_operacao, 561 | sum((ope.vl_negocio/case when ope.vl_fator_cotacao = 0 then 1 else ope.vl_fator_cotacao end) * ope.qt_negocio)as vl_total, 562 | sum(ope.qt_negocio)as qt_negocio, 563 | sum(ope.vl_negocio)as vl_negocio, 564 | ope.dc_hr_neg, ope.id_daytrade 565 | from dbo.tbl_operacao_corretora ope with (nolock) 566 | join dbo.tgr_cargas grc with (nolock) 567 | on ope.cd_carga = grc.cd_carga 568 | where grc.dt_referencia = @dt_inicio 569 | and grc.cd_produto = 10 570 | and ope.qt_negocio is not null 571 | and ope.vl_negocio is not null 572 | group by ope.cd_cliente, ope.dc_papel, ope.cd_mercado, ope.dc_mercado, ope.cd_contraparte, 573 | ope.cd_chave, ope.nr_negocio, ope.tp_neg, ope.dc_operacao, ope.dc_hr_neg, ope.id_daytrade 574 | 575 | -- executa calculo do percentual para perda ou ganho para operações DT 576 | exec dbo.spcr_calcula_percentual_perda_ganho @dt_inicio 577 | 578 | -- executa calculo do percentual para perda ou ganho para operações DT especifico para contraparte 579 | exec dbo.spcr_calcula_percentual_perda_ganho_contraparte @dt_inicio 580 | 581 | End 582 | else --Mensal 583 | 584 | Begin 585 | 586 | insert into #ttp_cliente (cd_cliente) 587 | select distinct cd_cliente 588 | from dbo.tbl_operacao_corretora with (nolock) 589 | where dt_ordem between @dt_inicio and @dt_final 590 | union 591 | --- Incluir todas masters - ALF 592 | select distinct a.cd_cliente 593 | from dbo.tcl_cliente_detalhe_bolsa a 594 | where cd_cliente_bolsa = cd_master 595 | 596 | set @vl_contador_total = @@rowcount; 597 | 598 | insert into ##ttp_movto(cd_cliente, cd_ativo, cd_mercado, dc_mercado, cd_contraparte, nr_ordem, nr_negocio, tp_negocio, 599 | tp_operacao, vl_total, qt_negocio, vl_negocio, hr_negocio, id_daytrade) 600 | select distinct ope.cd_cliente, ope.dc_papel, ope.cd_mercado, ope.dc_mercado, ope.cd_contraparte, ope.cd_chave, 601 | ope.nr_negocio, ope.tp_neg, ope.dc_operacao, 602 | sum((ope.vl_negocio/case when ope.vl_fator_cotacao = 0 then 1 else ope.vl_fator_cotacao end) * ope.qt_negocio)as vl_total, 603 | sum(ope.qt_negocio)as qt_negocio, 604 | sum(ope.vl_negocio)as vl_negocio, 605 | ope.dc_hr_neg, ope.id_daytrade 606 | from dbo.tbl_operacao_corretora ope with (nolock) 607 | where ope.dt_ordem between @dt_inicio and @dt_final 608 | and ope.qt_negocio is not null 609 | and ope.vl_negocio is not null 610 | group by ope.cd_cliente, ope.dc_papel, ope.cd_mercado, ope.dc_mercado, ope.cd_contraparte, 611 | ope.cd_chave, ope.nr_negocio, ope.tp_neg, ope.dc_operacao, ope.dc_hr_neg, ope.id_daytrade 612 | 613 | 614 | End 615 | 616 | End 617 | else 618 | begin 619 | insert into #ttp_cliente( cd_cliente ) 620 | values(@cd_cliente); 621 | End 622 | 623 | End 624 | 625 | --Atualiza a Quantidade de clientes que serão varridos 626 | 627 | if (@id_todos_clientes = 1) 628 | begin 629 | 630 | update dbo.tsv_status_varredura 631 | set vl_contador_total = @vl_contador_total 632 | where cd_varredura_aut = @cd_varredura_aut 633 | 634 | end 635 | 636 | --Declara o cursor com o resultado 637 | 638 | declare cr_clientes cursor 639 | for 640 | select distinct cd_cliente 641 | from #ttp_cliente 642 | order by cd_cliente 643 | 644 | open cr_clientes 645 | fetch next from cr_clientes into @cd_cliente_int 646 | if ((@id_resumir = 1) and (@id_todos_clientes = 1)) 647 | begin 648 | 649 | if convert(int, @cd_cliente_resumir) > 0 650 | while @cd_cliente_int <> @cd_cliente_resumir 651 | fetch next from cr_clientes into @cd_cliente_int 652 | 653 | end 654 | 655 | --Cursor Clientes 656 | 657 | while @@fetch_status = 0 658 | begin 659 | 660 | update dbo.tsv_status_varredura 661 | set cd_atual = @cd_cliente_int, 662 | vl_contador_atual = vl_contador_atual + 1, 663 | vl_tempo_carga_cliente = getdate() - @hr_ultimo_cliente 664 | where cd_varredura_aut = @cd_varredura_aut 665 | 666 | set @hr_ultimo_cliente = getdate() 667 | 668 | set @vl_total_mov = 0 669 | 670 | if (@id_automatica = 1) --Cursor Varreduras 671 | begin 672 | 673 | declare cr_varredura cursor 674 | 675 | for 676 | 677 | select rpe.cd_enquadramento, 678 | rpe.nm_stored_proc 679 | from dbo.tpr_relac_produto_enquad rpe with (nolock) 680 | join dbo.tpr_enquadramento enq with (nolock) on rpe.cd_enquadramento = enq.cd_enquadramento 681 | where rpe.cd_produto = @cd_produto_int 682 | and enq.id_mensal = @id_mensal 683 | and enq.id_status = 1 684 | 685 | end 686 | else 687 | begin 688 | 689 | declare cr_varredura cursor 690 | for 691 | 692 | select rpe.cd_enquadramento, 693 | rpe.nm_stored_proc 694 | from dbo.tpr_relac_produto_enquad rpe with (nolock) 695 | join dbo.tpr_relac_produto_enquad_param rpem with (nolock) on rpe.cd_produto = rpem.cd_produto 696 | and rpe.cd_enquadramento = rpem.cd_enquadramento 697 | join dbo.tpr_parametro_manual pm with (nolock) on rpem.cd_produto = pm.cd_produto 698 | and rpem.cd_enquadramento = pm.cd_enquadramento 699 | and rpem.cd_contador = pm.cd_contador 700 | where pm.id_varr_manual = 1 701 | and pm.cd_usuario = @cd_usuario 702 | and rpe.cd_produto = @cd_produto_int 703 | group by rpe.cd_produto, rpe.cd_enquadramento, rpe.nm_stored_proc 704 | order by rpe.cd_produto, rpe.cd_enquadramento 705 | 706 | end 707 | 708 | open cr_varredura 709 | fetch next from cr_varredura into @cd_enquadramento, @nm_stored_proc 710 | 711 | --Cursor Enquadramentos 712 | 713 | while @@fetch_status = 0 714 | 715 | begin 716 | 717 | if @cd_usuario is null 718 | 719 | begin 720 | 721 | set @dc_execucao_sp = 'exec ' + RTRIM(LTRIM(@nm_stored_proc)) + ' ' + CONVERT(VARCHAR,@cd_cliente_int) + ', ' + CONVERT(VARCHAR,@cd_enquadramento) + ', ' + 722 | CONVERT(VARCHAR,@cd_produto_int) + ', ''' + CONVERT(VARCHAR, @dt_inicio, 101) + ''', ''' + 723 | CONVERT(VARCHAR, @dt_final, 101) + ''', ' + CONVERT(VARCHAR,CONVERT(MONEY,@vl_total_mov)) + ', ' + 724 | CONVERT(VARCHAR,@id_automatica) + ', ' + CONVERT(VARCHAR, @id_resumir) 725 | 726 | end 727 | else 728 | begin 729 | 730 | set @dc_execucao_sp = 'exec ' + RTRIM(LTRIM(@nm_stored_proc)) + ' ' + CONVERT(VARCHAR,@cd_cliente_int) + ', ' + CONVERT(VARCHAR,@cd_enquadramento) + ', ' + 731 | CONVERT(VARCHAR,@cd_produto_int) + ', ''' + CONVERT(VARCHAR, @dt_inicio, 101) + ''', ''' + 732 | CONVERT(VARCHAR, @dt_final, 101) + ''', ' + CONVERT(VARCHAR,CONVERT(MONEY,@vl_total_mov)) + ', ' + 733 | CONVERT(VARCHAR,@id_automatica) + ', ' + CONVERT(VARCHAR, @id_resumir) + ', ' + convert(varchar, @cd_usuario) 734 | 735 | end 736 | 737 | exec sp_sqlexec @dc_execucao_sp; 738 | 739 | --print @dc_execucao_sp 740 | 741 | fetch next from cr_varredura into @cd_enquadramento, @nm_stored_proc 742 | 743 | end 744 | 745 | --Fecha cursor Enquadramentos 746 | 747 | close cr_varredura 748 | deallocate cr_varredura 749 | 750 | fetch next from cr_clientes into @cd_cliente_int 751 | 752 | if (@id_todos_clientes = 1) 753 | set @id_resumir = 0; 754 | 755 | end 756 | 757 | --Fecha cursor Clientes 758 | 759 | close cr_clientes 760 | deallocate cr_clientes 761 | 762 | if (@id_todos_clientes = 1) 763 | begin 764 | 765 | update dbo.tsv_status_varredura 766 | set dt_termino = getdate(), 767 | cd_atual = '000', 768 | id_terminado = 1 769 | where cd_varredura_aut = @cd_varredura_aut; 770 | 771 | end 772 | 773 | --Limpa a tabela temp 774 | 775 | delete from #ttp_cliente; 776 | fetch next from cr_produtos into @cd_produto_int 777 | 778 | end 779 | 780 | --Fecha cursor produtos 781 | 782 | close cr_produtos 783 | deallocate cr_produtos 784 | 785 | --Dropa a tabela temp 786 | 787 | drop table #ttp_cliente 788 | 789 | end try 790 | begin catch 791 | 792 | exec dbo.spgr_tratar_erro; 793 | 794 | end catch 795 | -------------------------------------------------------------------------------- /Procedures/1: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Procedures/10_Procedure_Average_Calculation.sql: -------------------------------------------------------------------------------- 1 | 2 | /****** Object: StoredProcedure [dbo].[spcc_aumento_vol] Script Date: 2023-01-31 13:30:21 ******/ 3 | SET ANSI_NULLS ON 4 | GO 5 | SET QUOTED_IDENTIFIER OFF 6 | GO 7 | ALTER procedure [dbo].[spcc_aumento_vol] 8 | @cd_cliente dt_cd_cliente, 9 | @cd_enquadramento smallint, 10 | @cd_produto smallint, 11 | @dt_inicio smalldatetime, 12 | @dt_final smalldatetime, 13 | @vl_total_mov float, 14 | @id_automatica bit, 15 | @id_resumir bit, 16 | @cd_usuario smallint = null 17 | as 18 | declare @vl_parametro1 float 19 | declare @vl_parametro2 float 20 | declare @vl_parametro3 float 21 | declare @cd_suspeita int 22 | declare @cd_status_suspeita int 23 | declare @dt_ultimo_mes smalldatetime 24 | declare @vl_dia char(2) 25 | declare @vl_mes char(2) 26 | declare @vl_ano char(4) 27 | declare @vl_media_mensal float 28 | declare @vl_percentual float 29 | declare @vl_dia_convertido char(7) 30 | declare @dt_limite smalldatetime 31 | declare @cd_resultado int 32 | declare @vl_isencao int 33 | declare @cd_unico int 34 | 35 | set dateformat mdy 36 | 37 | begin try 38 | 39 | exec @vl_isencao = spgr_verificar_isencao @cd_cliente, @cd_produto, @cd_enquadramento, @dt_final 40 | 41 | if (@vl_isencao = 0) 42 | begin 43 | 44 | exec spgr_achar_parametro @cd_produto, @cd_cliente, @cd_enquadramento, @cd_usuario, @id_automatica, 1, @vl_parametro1 output 45 | exec spgr_achar_parametro @cd_produto, @cd_cliente, @cd_enquadramento, @cd_usuario, @id_automatica, 2, @vl_parametro2 output 46 | exec spgr_achar_parametro @cd_produto, @cd_cliente, @cd_enquadramento, @cd_usuario, @id_automatica, 3, @vl_parametro3 output 47 | 48 | set @vl_dia = '01' 49 | 50 | if month(@dt_final) < 10 51 | set @vl_mes = '0' + convert(char(1), month(@dt_final)) 52 | else 53 | set @vl_mes = month(@dt_final) 54 | set @vl_ano = '%' 55 | set @vl_dia_convertido = convert(char, @vl_mes + '/' + @vl_dia + '/' + @vl_ano) 56 | set @vl_ano = year(@dt_final) 57 | set @dt_ultimo_mes = convert(smalldatetime, @vl_mes + '/' + @vl_dia + '/' + @vl_ano) 58 | set @vl_ano = year(@dt_final) - @vl_parametro1 59 | set @dt_limite = convert(smalldatetime, @vl_mes + '/' + @vl_dia + '/' + @vl_ano) 60 | 61 | if (@cd_produto = 1) 62 | begin 63 | 64 | if (@id_resumir = 1) 65 | begin 66 | 67 | delete from dbo.tgr_alertas 68 | where cd_cliente = @cd_cliente 69 | and dt_movimentacao = @dt_ultimo_mes 70 | and cd_enquadramento = @cd_enquadramento 71 | 72 | end 73 | 74 | select @vl_media_mensal = avg(vl_creditos) 75 | from (select 76 | (select sum(mhcc.vl_creditos) 77 | from dbo.tcc_mov_hist_conta_corr mhcc, dbo.tcc_cliente_conta_corr ccc 78 | where mb.dt_mes_ano = mhcc.dt_mes_ano 79 | and ccc.cd_agencia = mhcc.cd_agencia 80 | and ccc.nm_conta_corr = mhcc.nm_conta_corr 81 | and mhcc.dt_mes_ano >= @dt_limite 82 | and mhcc.dt_mes_ano < @dt_ultimo_mes 83 | and ccc.cd_cliente = @cd_cliente) as vl_creditos 84 | from dbo.tgr_mes_base mb) as vl_media_anual 85 | 86 | if @vl_media_mensal <> 0 87 | begin 88 | 89 | if ((@vl_total_mov >= (@vl_media_mensal * ((@vl_parametro2 / 100) + 1))) and 90 | (@vl_total_mov >= @vl_parametro3)) 91 | begin 92 | 93 | set @vl_percentual = ((@vl_total_mov / @vl_media_mensal) * 100) 94 | 95 | if not exists(select * 96 | from dbo.tgr_alertas 97 | where cd_cliente = @cd_cliente 98 | and dt_movimentacao = @dt_ultimo_mes 99 | and cd_enquadramento = @cd_enquadramento 100 | and round(vl_alerta,0) = round(isnull(@vl_percentual, 0),0) 101 | and round(vl_alerta1,0) = round(isnull(@vl_media_mensal, 0),0) 102 | and round(vl_alerta2,0) = round(isnull(@vl_total_mov, 0),0) 103 | and id_automatica = 1) 104 | begin 105 | 106 | select @cd_status_suspeita = cd_status_suspeita 107 | from dbo.tgr_status_suspeita 108 | where tp_status_suspeita = 0 109 | 110 | exec @cd_unico = dbo.spgr_inserir_relac_produto_unico @cd_cliente, @cd_produto, @cd_enquadramento 111 | 112 | insert into dbo.tgr_alertas (cd_cliente, cd_enquadramento, id_selecionado, id_automatica, cd_usuario, 113 | cd_status_atual, dt_alteracao, cd_produto, dt_movimentacao, 114 | vl_alerta, vl_alerta1, vl_alerta2, dt_varredura, cd_unico 115 | values(@cd_cliente, @cd_enquadramento, 0, @id_automatica, @cd_usuario, 116 | @cd_status_suspeita, getdate(), @cd_produto, @dt_ultimo_mes, 117 | isnull(@vl_percentual, 0), isnull(@vl_media_mensal, 0), isnull(@vl_total_mov, 0), getdate(), @cd_unico) 118 | 119 | 120 | end 121 | end 122 | end 123 | end 124 | end 125 | end try 126 | begin catch 127 | 128 | exec dbo.spgr_tratar_erro 129 | 130 | end catch 131 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | Ola, seja bem vindo ✨ 3 | 4 | Esse repositório contem modelos de Scripts em SQL que tornam nosso dia-a-dia mais facil, seja nos momentos de criar uma trabela, 5 | criar uma procedure, dar um grant em uma tabela entre outras diversas rotinas. 6 | 7 | Fiquem a vontade para utilizar e contribuir! 8 | -------------------------------------------------------------------------------- /SQL_Json/01_Importar_Arquivo_JsonSQL.sql: -------------------------------------------------------------------------------- 1 | /* Modelo do Arquivo Lido 2 | { 3 | "pessoas": { 4 | "pessoa": [ 5 | { 6 | "id": "1", 7 | "nm": "Priscila Laborão", 8 | "profissao": "Recrutadora" 9 | }, 10 | { 11 | "id": "2", 12 | "nm": "Tiragato Dakatola", 13 | "profissao": "Mágico" 14 | }, 15 | { 16 | "id": "3", 17 | "nm": "Rick Win", 18 | "profissao": "Usineiro" 19 | } 20 | ]}} 21 | */ 22 | 23 | use master 24 | go 25 | 26 | -------------------------------------------------- 27 | -- JSON => Variável 28 | -------------------------------------------------- 29 | declare @j varchar(max) = (select bulkcolumn from openrowset (bulk 'c:\tmp\pessoas.json', single_clob) a) 30 | select @j as [json] 31 | 32 | 33 | -------------------------------------------------- 34 | -- JSON => Variável => Tabela 35 | -------------------------------------------------- 36 | select 37 | * 38 | from openjson (@j, '$.pessoas.pessoa') 39 | with (id int, nm varchar(100), profissao varchar(100)) pessoas 40 | 41 | 42 | -------------------------------------------------- 43 | -- Tabela => json 44 | -------------------------------------------------- 45 | declare @pessoas table (id int, nm varchar(100), profissao varchar(100)) 46 | insert into @pessoas values 47 | (1, 'Priscila Laborão', 'Recrutadora'), 48 | (2, 'Tiragato Dakatola', 'Analista de TI'), 49 | (3, 'Ric Wyndfuck', 'Usineiro') 50 | 51 | select 52 | * 53 | from @pessoas as pessoa 54 | for json auto, root('pessoas') 55 | go 56 | 57 | -------------------------------------------------------------------------------- /SQL_Json/03_Importar_Json_Git.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JosiTubaroski/SQL/bdaa5cc2be2450715c5aff913c764940c94dd2a5/SQL_Json/03_Importar_Json_Git.sql -------------------------------------------------------------------------------- /SQL_Json/SQL_Json: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Tables/01_Create_Tabel.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | --- 01. Criação da Tabela Temporaria - dbo.ttp_riscos_baixados. 4 | 5 | IF (NOT EXISTS (select * from INFORMATION_SCHEMA.TABLES 6 | where TABLE_SCHEMA = 'dbo' 7 | and TABLE_NAME = 'ttp_riscos_baixados')) 8 | 9 | Begin 10 | 11 | SET ANSI_NULLS ON 12 | SET QUOTED_IDENTIFIER ON 13 | 14 | CREATE TABLE [dbo].[ttp_riscos_baixados]( 15 | [cpf_cnpj] [varchar](20) not NULL, 16 | [tp_pessoa] [char](1) not NULL, 17 | [dt_risco] [varchar](50) not NULL, 18 | [vl_risco] [int] NULL, 19 | [dc_risco] [varchar](50) NULL, 20 | [id_descon_regra][int] Null, 21 | [dt_cadastro] [smalldatetime] NULL) 22 | 23 | ALTER TABLE [dbo].[ttp_riscos_baixados] ADD CONSTRAINT [ttp_riscos_baixados_dt_cadastro] 24 | DEFAULT (getdate()) FOR [dt_cadastro] 25 | 26 | ALTER TABLE [dbo].[ttp_riscos_baixados] ADD CONSTRAINT [ttp_riscos_baixados_id_descon_regra] 27 | DEFAULT (1) FOR [id_descon_regra] 28 | 29 | End 30 | 31 | Go 32 | 33 | --- 02. Criação da Tabela Definitiva - dbo.tgr_riscos_baixados 34 | 35 | IF (NOT EXISTS (select * from INFORMATION_SCHEMA.TABLES 36 | where TABLE_SCHEMA = 'dbo' 37 | and TABLE_NAME = 'tgr_riscos_baixados')) 38 | 39 | 40 | Begin 41 | 42 | SET ANSI_NULLS ON 43 | SET QUOTED_IDENTIFIER ON 44 | 45 | CREATE TABLE [dbo].[tgr_riscos_baixados]( 46 | [cpf_cnpj] [varchar](20) not NULL, 47 | [tp_pessoa] [char](1) not NULL, 48 | [dt_risco] [varchar](50) not NULL, 49 | [vl_risco] [int] NULL, 50 | [dc_risco] [varchar](50) NULL, 51 | [id_descon_regra][int] Null, 52 | [dt_cadastro] [smalldatetime] NULL) 53 | 54 | 55 | ALTER TABLE [dbo].[tgr_riscos_baixados] ADD CONSTRAINT [tgr_riscos_baixados_dt_cadastro] 56 | DEFAULT (getdate()) FOR [dt_cadastro] 57 | 58 | ALTER TABLE [dbo].[tgr_riscos_baixados] ADD CONSTRAINT [tgr_riscos_baixados_id_descon_regra] 59 | DEFAULT (1) FOR [id_descon_regra] 60 | 61 | End 62 | 63 | Go 64 | 65 | IF (NOT EXISTS (select * from INFORMATION_SCHEMA.TABLES 66 | where TABLE_SCHEMA = 'dbo' 67 | and TABLE_NAME = 'tgr_riscos_cpfs_nao_loc')) 68 | 69 | Begin 70 | 71 | SET ANSI_NULLS ON 72 | SET QUOTED_IDENTIFIER ON 73 | 74 | CREATE TABLE [dbo].[tgr_riscos_cpfs_nao_loc]( 75 | [cpf_cnpj] [varchar](20) not NULL, 76 | [tp_pessoa] [char](1) not NULL, 77 | [dt_risco] [varchar](50) not NULL, 78 | [vl_risco] [int] NULL, 79 | [dc_risco] [varchar](50) NULL, 80 | [id_descon_regra][int] Null, 81 | [dt_cadastro] [smalldatetime] NULL) 82 | 83 | 84 | ALTER TABLE [dbo].[tgr_riscos_cpfs_nao_loc] ADD CONSTRAINT [tgr_riscos_cpfs_nao_loc_dt_cadastro] 85 | DEFAULT (getdate()) FOR [dt_cadastro] 86 | 87 | ALTER TABLE [dbo].[tgr_riscos_cpfs_nao_loc] ADD CONSTRAINT [tgr_riscos_cpfs_nao_loc_id_descon_regra] 88 | DEFAULT (1) FOR [id_descon_regra] 89 | 90 | End 91 | 92 | IF (NOT EXISTS (select * from INFORMATION_SCHEMA.TABLES 93 | where TABLE_SCHEMA = 'dbo' 94 | and TABLE_NAME = 'ttp_clientes_item_risco_manual')) 95 | 96 | Begin 97 | 98 | SET ANSI_NULLS ON 99 | SET QUOTED_IDENTIFIER ON 100 | 101 | CREATE TABLE [dbo].[ttp_clientes_item_risco_manual]( 102 | [cd_cliente] int not null, 103 | [cpf_cnpj] [varchar](20) not NULL, 104 | [dt_cadastro] [smalldatetime] NULL) 105 | 106 | ALTER TABLE [dbo].[ttp_clientes_item_risco_manual] ADD CONSTRAINT [ttp_clientes_item_risco_manual_dt_cadastro] 107 | DEFAULT (getdate()) FOR [dt_cadastro] 108 | 109 | End 110 | -------------------------------------------------------------------------------- /Tables/02_Alter_Table_addfield.sql: -------------------------------------------------------------------------------- 1 | 2 | --- Caso o campo não exista o campo na tabela então será adicionado 3 | 4 | If not exists (Select top 1 T.name AS Tabela,C.name AS Coluna 5 | from sys.sysobjects as T (nolock) 6 | inner join sys.all_columns AS C (NOLOCK) ON T.id = C.object_id AND T.XTYPE = 'U' 7 | Where T.name = 'tgr_funcionario' and C.NAME = 'dt_nascimento') 8 | 9 | ALTER TABLE dbo.tgr_funcionario 10 | ADD dt_nascimento VARCHAR(30) NULL 11 | -------------------------------------------------------------------------------- /Tables/03_Drop_Table.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | --- 01. Dropar Tabela caso exista na base 4 | --- Movimentacoes Conta Corrente - Matera 5 | 6 | IF (EXISTS (select * from INFORMATION_SCHEMA.TABLES 7 | where TABLE_SCHEMA = 'dbo' 8 | and TABLE_NAME = 'tb_movimentacao_cc_matera')) 9 | 10 | Begin 11 | 12 | drop table dbo.vw_tb_movimentacao_cc_matera 13 | 14 | end 15 | -------------------------------------------------------------------------------- /Tables/04_Drop_Field.sql: -------------------------------------------------------------------------------- 1 | 2 | 3 | ALTER TABLE minha_tabela 4 | DROP COLUMN exemplo_coluna; 5 | -------------------------------------------------------------------------------- /Tables/Tables: -------------------------------------------------------------------------------- 1 | 2 | --------------------------------------------------------------------------------