Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Cusor / Repeating code help

Author  Topic 

zanq
Starting Member

3 Posts

Posted - 2012-09-06 : 21:50:17
Hi I'm fairly new to SQL and I would like to insert data into a table from other tables (like the code below), But I obviously know that repeating code is just wrong. I think I want to create a lookup table for the tables I want to pull from and reference that (there are many) but I don't know how to 'make a loop or cursor'. Can somebody please direct me in the right direction or show an example of what I should be doing here. Thanks.

INSERT INTO SomeTable
SELECT a.ColumnOne,a.ColumnTwo,a.ColumnThree
FROM TableOne a

INSERT INTO SomeTable
SELECT b.ColumnOne,b.ColumnTwo,b.ColumnThree
FROM TableTwo b

INSERT INTO SomeTable
SELECT c.ColumnOne,c.ColumnTwo,c.ColumnThree
FROM TableThree c

chadmat
The Chadinator

1974 Posts

Posted - 2012-09-07 : 03:02:20
What is wrong with those inserts? You don't need (And shouldn't want) a cursor. You could consolidate to 1 query with a union if you wanted to. ie

INSERT INTO SomeTable
SELECT a.ColumnOne,a.ColumnTwo,a.ColumnThree
FROM TableOne a
UNION
SELECT b.ColumnOne,b.ColumnTwo,b.ColumnThree
FROM TableTwo b
UNION
SELECT c.ColumnOne,c.ColumnTwo,c.ColumnThree
FROM TableThree c


-Chad
Go to Top of Page
   

- Advertisement -