Until this line
EXEC sp_executesql @InsertQuery, N'@product_id BIGINT OUTPUT', @product_id OUTPUT
I managed to obtain the product_id correctly, the problem is when inserting in the @InsertQuery2, it inserts product_id = NULL
DECLARE @InsertQuery NVARCHAR(MAX)
SET @InsertQuery = '
INSERT INTO ' + QUOTENAME(@bdEmpresa) + '.dbo.Producto (
producto_codigo,
producto_codigoanterior,
producto_status
)
OUTPUT INSERTED.producto_id
SELECT
producto_codigo,
producto_codigoanterior,
producto_status
FROM #TempProducto'
-- Ejecutar la consulta de inserción y capturar el producto_id generado
EXEC sp_executesql @InsertQuery, N'@producto_id BIGINT OUTPUT', @producto_id OUTPUT
-- Insertar datos de proveedores en la tabla de la base de datos de la empresa
DECLARE @InsertQuery2 NVARCHAR(MAX)
SET @InsertQuery2 = '
INSERT INTO ' + QUOTENAME(@bdEmpresa) + '.dbo.ProductoProveedor (
producto_id,
proveedor_ruc,
proveedor_dscto
)
SELECT
@producto_id,
proveedor_ruc,
proveedor_dscto
FROM #TempProveedores'
-- Ejecutar la consulta de inserción
EXEC sp_executesql @InsertQuery2, N'@producto_id BIGINT', @producto_id
I need to pass the id obtained after registration in the Product table to @InsertQuery2 since I need to insert it there too
OUTPUTreturns a whole resultset. To capture and reuse it in another query you need to addINTO someTable.Also, instead of injecting the database name, you can construct a variable containing
SomeDb.sys.sp_executesqland then doEXEC @procIf you are using temp tables just to pass data between procedures then you should consider Table Types and Table Valued Parameters, as these are better designed to do that.