Write data to a based table and two other tables

0

Hello! I am new to transact sql and would like and have the following situation. I have a tableA that has the column list of a second tableB. That's it! In table B the column names are the same as those stored in table A. Then you would use the SELECT information in table B and store it in a third tabelac. It would be something like:

@Coluna = SELECT nomecoluna FROM tabelaA;
WHILE (!@Coluna)
BEGIN
INSERT INTO TABLE tabelaC (data, tag) 
SELECT data, @Coluna from tabelaB;
END

Note: The column tag in tableC would receive as value the column name (@column)

I hope someone is encouraged to help me! Abs!

    
asked by anonymous 25.01.2018 / 23:28

2 answers

0

I think this works:

declare @query nvarchar(max), @nome varchar(50)
declare @temp Table (nomecoluna nvarchar(50))

--SALVE OS REGISTROS COM OS NOMES DAS COLUNAS EM @TABLE
insert into @temp
select * from TabelaA

--ENQUANTO EXISTIR REGISTRO EM @TABLE...
while exists (select nomecoluna from @temp)

begin
--...CRIA A QUERY PARA PEGAR DE UMA TABELA E INSERIR NA OUTRA
set @nome = (select top 1 nomecoluna from @temp);

set @query = 'insert into TabelaC (tag) select '+@nome+' from TabelaB';
--EXECUTE A QUERY
exec (@query)
--E APAGUE O REGISTRO DE @TEMP
delete from @temp where nomecoluna = @nome

end
    
26.01.2018 / 01:00
0

One suggestion would be to use the select into statement. It will automatically create the table after into It would need to rename existing tables.

SELECT colunaA, colunaB, coluna C 
INTO TabelaB
FROM TabelaA
WHERE ...

SELECT colunaA, colunaB, coluna C 
INTO TabelaC
FROM TabelaB
WHERE ...
    
26.01.2018 / 01:28