I have the following stored procedure, to save or update according to the value of nOption, registration of a table of products. In it I have a bar code and an alphanumeric code and I want to check before saving or updating that it is not repeated, that is to say that do not save 2 products with the same barcode or alphanumeric:
CREATE DEFINER=`root`@`localhost` PROCEDURE `USP_Guardar_pr`(IN
nOpcion int,
nCodigo_pr int,
cDescripcion_pr varchar(100),
cca_pr varchar(100),
ccb_pr varchar(100),
nCodigo_ma int,
nCodigo_um int,
nCodigo_ca int,
nStock_min decimal(10,2),
nStock_max decimal(10,2),
nPu_venta decimal(10,2)
)
BEGIN
declare xCodigo int ;
declare fFecha datetime ;
set fFecha = CURDATE();
if nOpcion=1 THEN -- Nuevo Registro
begin
insert into TB_PRODUCTOS(codigo_barra,codigo_an,descripcion_pr,
codigo_ma,
codigo_um,
codigo_ca,
stock_min,
stock_max,
pu_venta,
fecha_crea,
fecha_modifica,
estado)
values(ccb_pr,cca_pr,
cDescripcion_pr,
nCodigo_ma,
nCodigo_um,
nCodigo_ca,
nStock_min,
nStock_max,
nPu_venta,
fFecha,
fFecha,
1);
set xCodigo= @@IDENTITY ;-- obtiene el código que se generó automáticamente
insert into TB_STOCK_PRODUCTOS(codigo_pr,
codigo_al,
stock_actual,
pu_compra)
select xCodigo,
codigo_al,
0.00,
0.00
from TB_ALMACENES;
end;
else -- Actualizar registro
begin
update TB_PRODUCTOS set descripcion_pr=cDescripcion_pr,
codigo_barra=ccb_pr,
codigo_an=cca_pr,
codigo_ma=nCodigo_ma,
codigo_um=nCodigo_um,
codigo_ca=nCodigo_ca,
stock_min=nStock_min,
stock_max=nStock_max,
pu_venta=nPu_venta,
fecha_modifica=fFecha
where codigo_pr=nCodigo_pr;
insert into TB_STOCK_PRODUCTOS(codigo_pr,
codigo_al,
stock_actual,
pu_compra)
select nCodigo_pr,
codigo_al,
0.00,
0.00
from TB_ALMACENES
where codigo_al not in (select codigo_al from TB_STOCK_PRODUCTOS where codigo_pr=nCodigo_pr) ;
end;
END IF;
END
Or can it also be convenient for me to execute another previous store procedure from C# and do the verification? I work with .NET
You could create
unique index
for those fields and with an error handler catch the duplicate index error (error 1062).