Pregunta

How do I loop through a SQL table's rows and convert them into rows for another table? I have a table with an Id, Timestamp, IpAddress, and two varchar(500)'s that I want to change to another table with an Id, StartTime and EndTime initialized to the Timestamp, no IpAddress, and foreign keys to tables holding initially each their varchar(500). Thanks!

¿Fue útil?

Solución 2

If the table already exists, the syntax is:

insert into TargetTable
(field1, field2, etc)
select field1, field2, etc
from OtherTables
where whatever

Otros consejos

You can use select ... into to create a new table from a select statement:

select  orig.Id
,       orig.Timestamp
,       fk1.Id
,       fk2.id
into    NewTable
from    OldTable orig
join    ForeignKey1 fk1
on      fk1.value = orig.varchar_1
join    ForeignKey2 fk2
on      fk2.value = orig.varchar_2

alter table NewTable add constraint FK_NewTable_ForeignKey1 
    foreign key references ForeignKey1(Id)

alter table NewTable add constraint FK_NewTable_ForeignKey2
    foreign key references ForeignKey2(Id)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top