Is it possible to generate a script from a table, from an SQL command?

4

I would like to generate a script to create a table, from a SQL command so I could build a program that would be able to clone tables.

I'm using SQL Server 2008 R2 and need to implement a table cloning routine, within an application written in VB.Net.

In this way, I would choose the bank and the tables of this bank that would be cloned and then I would throw them into another database that would receive this mirroring.

    
asked by anonymous 13.10.2014 / 14:42

1 answer

12

There are many ways to do it, some more within the pattern, others not so much, some more simple, some more specific but I think this is what you want:

CREATE TABLE tabela_nova AS
   (SELECT * FROM tabela_existente);

I do not know if it works in all databases (tested in PostgreSQL), but you did not specify any. Note that you only copy the table, nothing that might be related to it.

If you just want to copy the structure without copying the data, just put a condition that is certainly false:

CREATE TABLE tabela_nova AS
   (SELECT * FROM tabela_existente WHERE 1=2);

For SQL Server it can be:

SELECT * INTO tabela_nova From tabela_existente WHERE 1=2;

As the above code does not seem to work in MySQL, maybe this will only work on it:

CREATE TABLE tabela_nova LIKE tabela_existente;

In SQLite it is to work the standard way but it can have some side effects like type loss. There is another way. You can pick up how the original table was easily created in SQLite itself. It stores the SQL command that was used to create the original. From there you can adapt to create your new table. The data is stored in the sqlite_master table:

SELECT sql FROM sqlite_master WHERE type='table' AND name='mytable';

I placed GitHub for future reference.

    
13.10.2014 / 14:46