Generador de INSERT INTO

Generador de INSERT INTO
El siguiente procedimiento almacenado, surge como herramienta para importar datos de TABLAS entre diferentes Bases de Datos SQL Server, que se presumen tienen la misma estructura.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Eduardo Marvil
-- Create date: 21/08/2016
-- Description: Obtiene en Texto INSERT INTO para una tabla
-- =============================================
ALTER PROCEDURE [dbo].[usp_InsertInto]
 @esquema NVARCHAR(255) = '', 
 @tabla NVARCHAR(255) = '',
 @desdeBD NVARCHAR(255) = ''
AS
BEGIN
 SET NOCOUNT ON;
 DECLARE @cCampo VARCHAR(MAX)
 DECLARE @cFields VARCHAR(MAX)
 SET @cFields = ''
 DECLARE Cur_Campos CURSOR LOCAL FORWARD_ONLY FOR   
   SELECT name 
   FROM sys.columns 
   WHERE object_id = OBJECT_ID(@esquema + '.' + @tabla) 
   AND is_computed = 0

 OPEN Cur_Campos
 FETCH Cur_Campos INTO @cCampo

 WHILE (@@FETCH_STATUS = 0)
 BEGIN
  SET @cFields = @cFields + @cCampo + ','
  FETCH Cur_Campos INTO @cCampo
 END -- Fin del bucle WHILE

 CLOSE Cur_Campos
 DEALLOCATE Cur_Campos

 -- SI TIENE IDENTITITY
 PRINT 'BEGIN TRY'
 PRINT '    TRUNCATE TABLE ' + @esquema + '.' + @tabla 
 PRINT 'END TRY'
 PRINT 'BEGIN CATCH'
 PRINT '    DELETE FROM ' + @esquema + '.' + @tabla 
 PRINT 'END CATCH'

 IF EXISTS(SELECT NAME FROM sys.columns WHERE object_id = OBJECT_ID(@esquema + '.' + @tabla) and is_identity = 1) BEGIN
  PRINT 'SET IDENTITY_INSERT ' + @esquema + '.' + @tabla + ' ON'
 END

 SET @cFields = SUBSTRING(@cFields,1, LEN(@cFields)-1)
 PRINT 'INSERT INTO ' + @esquema + '.' + @tabla + '(' + @cFields + ')'
 PRINT 'SELECT ' + @cFields + ' FROM ' + @desdeBD + '.' + @esquema + '.' + @tabla
 IF EXISTS(SELECT NAME FROM sys.columns WHERE object_id = OBJECT_ID(@esquema + '.' + @tabla) and is_identity = 1) BEGIN
  PRINT 'SET IDENTITY_INSERT ' + @esquema + '.' + @tabla + ' OFF'
 END
 PRINT ''
END

Ejemplo de Uso:
EXECUTE usp_InsertInto ‘dbo’,’tabla’,’BD’

Donde: ‘dbo’ es el esquema, ‘tabla’ es la tabla que queremos llenar y ‘BD’ es la Base de Datos de donde se traerán los datos; el procedimiento regresa:

BEGIN TRY
TRUNCATE TABLE dbo.tabla
END TRY
BEGIN CATCH
DELETE FROM dbo.tabla
END CATCH
SET IDENTITY_INSERT dbo.tabla ON
INSERT INTO dbo.tabla(id_variable,descripcion,descripcion_larga,id_udm,id_modulo,id_systema,query,cantidad,valor,resultado,inactivo)
SELECT id_variable,descripcion,descripcion_larga,id_udm,id_modulo,id_systema,query,cantidad,valor,resultado,inactivo FROM BD.dbo.tabla
SET IDENTITY_INSERT dbo.tabla OFF

Estas líneas solamente se copian y pegan en el cliente de SQL Server y se ejecutan, si las tablas tienen la misma estructura, debe funcionar. Primero trata de truncar la tabla, si no puede entonces ejecuta un DELETE, si la tabla tiene un IDENTITY lo desactiva para luego ejecutar el INSERT INTO y posteriormente vuelve a activar el IDENTITY.

Scroll al inicio