Como crear un script que haga inserts de los registros de una tabla (SQL Server)

PROBLEMA: Tengo una tabla con registros y quiero llevar estos registros a otra tabla con el mismo nombre en otra base de datos, en un servidor que no están conectados.

En Creates a data insert script from a table, Nigel Rivett publica un script bueno para crear las sentencias insert, con los valores de tablas que ya existen. Es bueno para pasar los registros que me funcionan correctamente en el ambiente de desarrollo a produccion, a traves de un script.

Copio el script para crear el stored procedure, que luego puede usarse para crear el script. Me resultó muy util.
Tiene un problema con el formato de las fechas, pero es facilmente solucionable.


if exists (select * from sysobjects where id = object_id(N'[dbo].[sp_CreateDataLoadScript]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_CreateDataLoadScript]
GO

Create Procedure sp_CreateDataLoadScript
@TblName varchar(128)
as
/*
exec sp_CreateDataLoadScript 'MyTable'
*/


create table #a (id int identity (1,1), ColType int, ColName varchar(128))

insert #a (ColType, ColName)
select case when DATA_TYPE like '%char%' then 1 else 0 end ,
COLUMN_NAME
from information_schema.columns
where TABLE_NAME = @TblName
order by ORDINAL_POSITION

if not exists (select * from #a)
begin
raiserror('No columns found for table %s', 16,-1, @TblName)
return
end

declare @id int ,
@maxid int ,
@cmd1 varchar(7000) ,
@cmd2 varchar(7000)

select @id = 0 ,
@maxid = max(id)
from #a

select @cmd1 = 'select '' insert ' + @TblName + ' ( '
select @cmd2 = ' + '' select '' + '
while @id < @maxid begin select @id = min(id) from #a where id > @id

select @cmd1 = @cmd1 + ColName + ','
from #a
where id = @id

select @cmd2 = @cmd2
+ ' case when ' + ColName + ' is null '
+ ' then ''null'' '
+ ' else '
+ case when ColType = 1 then ''''''''' + ' + ColName + ' + ''''''''' else 'convert(varchar(20),' + ColName + ')' end
+ ' end + '','' + '
from #a
where id = @id
end


select @cmd1 = left(@cmd1,len(@cmd1)-1) + ' ) '' '
select @cmd2 = left(@cmd2,len(@cmd2)-8) + ' from ' + @tblName

select '/*' + @cmd1 + @cmd2 + '*/'

exec (@cmd1 + @cmd2)
drop table #a

go

Comentarios

  1. LE HICE ALGUNOS CABIOS PAR LAS FECHAS Y SOPORTAR TABLAS CON MAS COLUMNAS, ASI COMO GENERAR PARA VARIAS AL TIEMPO


    ALTER Procedure [dbo].[sp_CreateDataLoadScript]
    @TblName varchar(128)
    as
    create table #a (id int identity (1,1), ColType int, ColName varchar(128))

    insert #a (ColType, ColName)
    select case when DATA_TYPE like '%char%' then 1 when DATA_TYPE like '%date%' then 2 else 0 end ,
    COLUMN_NAME
    from information_schema.columns
    where TABLE_NAME = @TblName
    order by ORDINAL_POSITION


    if not exists (select * from #a)
    begin
    raiserror('No columns found for table %s', 16,-1, @TblName)
    return
    end

    declare @id int ,
    @maxid int ,
    @cmd1 varchar(8000) ,
    @cmd2 varchar(8000), @cmd2Prima varchar(8000)
    set @cmd2Prima = ' '
    select @id = 0 ,
    @maxid = max(id)
    from #a

    select @cmd1 = 'select 1, '' insert ' + @TblName + ' ( '
    select @cmd2 = ' + '' select '' + '
    while @id < @maxid begin
    select @id = min(id) from #a where id > @id
    select @cmd1 = @cmd1 + ColName + ','
    from #a
    where id = @id

    select @cmd2 = @cmd2
    + ' case when ' + ColName + ' is null '
    + ' then ''null'' '
    + ' else '
    + case when ColType = 1 then ''''''''' + ' + ColName + ' + '''''''''
    when ColType = 2 then ''''''''' + convert(varchar(10),' + ColName + ', 103) + '''''''''
    else 'convert(varchar(20),' + ColName + ')' end
    + ' end + '','' + '
    from #a
    where id = @id
    if len(@cmd2) > 7000
    begin
    set @cmd2Prima = @cmd2
    set @cmd2 = ' '
    end
    end

    --averiguar si hay columna identity
    declare @cur cursor , @ColName varchar(128)
    SET @cur = CURSOR SCROLL KEYSET FOR select ColName from #a
    OPEN @cur
    FETCH NEXT FROM @cur into @ColName
    declare @ident bit
    set @ident = 0
    while @@fetCh_status = 0 and @ident = 0
    BEGIN
    if (SELECT COLUMNPROPERTY( OBJECT_ID(@tblName),@ColName,'IsIdentity')) = 1
    set @ident = 1
    FETCH NEXT FROM @cur into @ColName
    end
    close @cur
    deallocate @cur

    select @cmd1 = left(@cmd1,len(@cmd1)-1) + ' ) '' '
    select @cmd2 = left(@cmd2,len(@cmd2)-8) + ' from ' + @tblName

    declare @cmd3 varchar(500), @cmd4 varchar(100)

    if @ident = 1
    begin
    set @cmd3 = 'select -1, '' set identity_insert ' + @tblName + ' on '' union '
    set @cmd4 = ' union select 9999999, '' set identity_insert ' + @tblName + ' off '' '
    end
    else
    begin
    set @cmd3 = ' '
    set @cmd4 = ' '
    end
    set @cmd3 = @cmd3 + 'select -2, '' set dateformat dmy '''
    set @cmd3 = @cmd3 + ' union '



    --select '/*' + @cmd3 + @cmd1 + @cmd2Prima + @cmd2 + @cmd4 + '*/'

    exec (@cmd3 + @cmd1 + @cmd2Prima + @cmd2 + @cmd4)
    drop table #a



    GO
    /****** Objeto: StoredProcedure [dbo].[sp_CreateDataLoadAllTables] Fecha de la secuencia de comandos: 04/22/2008 17:54:36 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

    ALTER proc [dbo].[sp_CreateDataLoadAllTables] @fitro varchar(100)
    as

    --exec sp_CreateDataLoadAllTables '%Empleado%'


    declare @cur cursor , @ColName varchar(128)
    SET @cur = CURSOR SCROLL KEYSET FOR select Table_name from information_schema.tables
    where Table_name like @fitro
    order by Table_name
    OPEN @cur
    FETCH NEXT FROM @cur into @ColName
    while @@fetCh_status = 0
    BEGIN
    exec sp_CreateDataLoadScript @ColName
    FETCH NEXT FROM @cur into @ColName
    end
    close @cur
    deallocate @cur

    VISITA WWW.CEROESTRES.COM

    ResponderBorrar
  2. Boris:
    Voy a probar los cambios que propones y despues te cuento.

    Gracias!
    Enrique

    ResponderBorrar
  3. Gracias Enrique por tus aportaciones.
    Como sabes, no hay casi nada en la red sobre como subir y bajar IMAGENES a BBDD Mysql con PHP, quizás tambien Dreanweaaver.

    ¿PODRIAS HACERNOS UN EXTENSO, A LA VEZ QUE COMPRESNSIBLE, SCRIPT SOBRE COMO MANEJAR FOTOS ENN BBDD?

    gRACIS ANTICIPADAS

    ResponderBorrar
  4. Anonimo:
    En
    http://php.about.com/od/phpwithmysql/ss/Upload_file_sql.htm
    podes encontrar un ejemplo detallado de como hacer lo que queres.

    Enrique

    ResponderBorrar
  5. No funciona cuando hay campos de tipo Image... Alguien podria ayudar a que funcione cuando la tabla tiene campos image...

    ResponderBorrar

Publicar un comentario

1) Lee el post
2) Poné tu opinión sobre el mismo.
Todos los comentarios serán leidos y la mayoría son publicados.

Entradas más populares de este blog

La nefasta influencia del golero de Cacho Bochinche en el fútbol uruguayo

Aplicación monolítica o distribuida?

Funcionalidades de GeneXus que vale la pena conocer: DATE Constants.