Union identical tables in one view

Please support our MS SQL advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Nov 2009
Posts: 6
Reputation: elauri is an unknown quantity at this point 
Solved Threads: 0
elauri elauri is offline Offline
Newbie Poster

Union identical tables in one view

 
0
  #1
21 Days Ago
Hello all,

my first post.

I have identical tables in my db. Is there a way to create a view with dynamic query to combine/union all the identical tables into one view?

dbo.table.x-1
dbo.table.x-2
dbo.table.x-3
dbo.table.x-{n}
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 217
Reputation: mail2saion is an unknown quantity at this point 
Solved Threads: 31
mail2saion's Avatar
mail2saion mail2saion is offline Offline
Posting Whiz in Training
 
0
  #2
21 Days Ago
You can create a view dynamically in the following way:
  1. Declare @SQL nVarChar(1000)
  2.  
  3. SELECT @SQL = 'Create View Auths AS (SELECT au_id, au_lname, au_fname FROM Authors)'
  4.  
  5. Execute pubs.dbo.sp_executesql @sql
MARK AS SOLVED if its help you.

REGARDS
MCTS - Shawpnendu bikash maloroy
http://shawpnendu.blogspot.com
Reply With Quote Quick reply to this message  
Join Date: Nov 2009
Posts: 6
Reputation: elauri is an unknown quantity at this point 
Solved Threads: 0
elauri elauri is offline Offline
Newbie Poster
 
0
  #3
20 Days Ago
Thanks for your answer. Sorry I give a better explanation.

Currently I have solved the union problem by creating a cursor and creating a new table to insert all other tables.

  1. DECLARE CURSOR_TABLES CURSOR FOR
  2. SELECT name
  3. FROM sys.TABLES
  4. WHERE name LIKE '%TABLE-%
  5.  

Here I created the cursor with all the tables I want to combine. The tables have identical structure.

  1. OPEN CURSOR_TABLES
  2. FETCH NEXT FROM CURSOR_TABLES INTO @TableName
  3. WHILE @@FETCH_STATUS <> -1
  4. BEGIN
  5. SET @SQLInsertCmd = 'INSERT INTO dbo.TABLE SELECT table_names FROM ' + @TableName
  6. EXEC (@SQLInsertCmd)
  7.  
  8. FETCH NEXT FROM CURSOR_TABLES INTO @TableName
  9. END
Reply With Quote Quick reply to this message  
Join Date: Nov 2009
Posts: 6
Reputation: elauri is an unknown quantity at this point 
Solved Threads: 0
elauri elauri is offline Offline
Newbie Poster
 
0
  #4
20 Days Ago
Actually I found out I can use my Cursor to create a sql statement
  1. CREATE VIEW ViewTables AS
  2. SELECT * FROM table1
  3. UNION ALL
  4. SELECT * FROM table2
  5. ...
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC