Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12»»

UNION Help Expand / Collapse
Author
Message
Posted Monday, September 10, 2012 3:10 AM
Grasshopper

GrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopperGrasshopper

Group: General Forum Members
Last Login: Monday, May 12, 2014 4:22 AM
Points: 13, Visits: 103
I have a database that contains a number of individual tables for each sales agents. I need to find a way to set up a query that dynamically unions all tables in the database, so as an new agent joins the business their table will automatically be picked up in the union. The idea being, I have 1 table that contains the information for all agents.

Any help would be greatly appreciated.

Many thanks in advance.

Tables in database ( example)
David
John
Steven


Columns in agents table ( example)
,[Start_Time]
,[End_Time]
,[Record_Type]
,[User_Action]
,[Direction]
,[Action_Data]
,[From_addr]
,[To_addr]
,[Subject]
,[Detail]
,[Company]
,[Contact]
,[FullPath]
Post #1356604
Posted Monday, September 10, 2012 3:20 AM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Tuesday, November 27, 2012 9:02 AM
Points: 114, Visits: 140

It would be possible to build a dynamic query that checks for tablenames, and checks if those tables have the columns corresponding to an agent table, and if so includes them in the union, but it would be quite complex, and from an SQL Server point of view, like using a Ferrari to plough a field.

Much better to use the relational database in the way it is designed to be used.

Create an Agents_Name Table, with an ID column
Add and AgentName_ID column to your Agent table.

This way, all agents share the same Agent Table, but are identified by AgentName_ID

Then instead of a union, you only query one table, possibly joining to the AgentName table to get the name if needed.
Post #1356606
Posted Monday, September 10, 2012 6:07 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Monday, August 25, 2014 7:14 AM
Points: 7,197, Visits: 6,341
DBayliss, if you can follow t.brown's advice, that would be the best solution to your issue. If you are constrained from making changes to the existing schema, here are a couple of thoughts.

1) Create a new table per t.brown's advice and have a job that inserts the new agent information when a new agent is added. Then use that to hit all the other tables. You could (though this would be poor relational programming) even include the agent's table name as a column in the agent's table.

2) Loop through information_schema.tables and pull the table_name values from there. Regardless of how you dynamically pull these table names, you would have to have an idea of what separates these agent tables from all the other tables. Or you could just throw the agent table names into a brand new table (maybe even that table into a new DatabaseAdmin database) that you can pull the agent tables from. Use Dynamic SQL to do your UNION / UNION ALL.

BTW, I don't really recommend this as your best option.

3) Use a staging table to merge all the agent table data into, then query off of that. You could use any number of things to keep the staging table updated, like replication, or a regular LEFT OUTER JOIN type of INSERT statement, or even an SSIS package with slowly changing dimensions. The options depend on your data, really.



Brandie Tarvin, MCITP Database Administrator

Webpage: http://www.BrandieTarvin.net
LiveJournal Blog: http://brandietarvin.livejournal.com/
On LinkedIn!, Google+, and Twitter.

Freelance Writer: Shadowrun
Latchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.
Post #1356681
Posted Monday, September 10, 2012 6:39 AM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Wednesday, July 30, 2014 10:34 AM
Points: 386, Visits: 624
If you created this database structure, please read up on database normalisation and correct the structure before you go any further down this design.

If someone else created it and they are still around, go and puch them on the nose.

If they are not around go and punch the wall.

If you have to stick with this design, I would create a table of agents and a stored procedure that writes a view using dynamic SQL that is triggered every time the agents table is altered.


the view with UNION ALL the same query once for each agent table

The problem is that any other view or stored procedure that uses that generated view will also need to be recompiled every time the view changes.


SERIOUSLY, get the data normalised.


Post #1356694
Posted Monday, September 10, 2012 6:52 AM
SSC-Enthusiastic

SSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-EnthusiasticSSC-Enthusiastic

Group: General Forum Members
Last Login: Tuesday, November 27, 2012 9:02 AM
Points: 114, Visits: 140
DBayliss - I looked at your other posts, and I think you've been landed with this task to maintain someone elses questionable code.

Brandie's Idea (2), while not ideal, can be done as follows.

First get the tables of type Agent - using the column names common to the Agent Tables as shown here (you can extend it to all the column names for greater accuracy)

SELECT DISTINCT T.TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES AS T
JOIN INFORMATION_SCHEMA.COLUMNS AS C ON C.TABLE_NAME = T.TABLE_NAME
WHERE C.COLUMN_NAME IN ( 'Start_Time' , 'End_Time', 'Record_Type', 'User_Action')

Then Dynamically create a SELECT statement from each of these, UNIONing them all together I've only included a few of the columns in the select - as follows.


Note: The fancy row_number bit is just to identify the last row, so it doesn't get a UNION ALL following.



DECLARE @SQL VARCHAR(MAX)
SET @SQL = '';
;WITH AgentTables AS (
SELECT DISTINCT T.TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES AS T
JOIN INFORMATION_SCHEMA.COLUMNS AS C ON C.TABLE_NAME = T.TABLE_NAME
WHERE C.COLUMN_NAME IN ( 'Start_Time' , 'End_Time', 'Record_Type', 'User_Action')
), NumberedTables AS (
SELECT TABLE_NAME, ROW_NUMBER() OVER (ORDER BY TABLE_NAME) AS RowNum
FROM AgentTables
)
SELECT @SQL = @SQL + ' SELECT ''' + TABLE_NAME +''' AS AgentName, [Start_Time], [End_Time], [Record_Type] FROM ' + TABLE_NAME +
CASE WHEN RowNum = (SELECT COUNT(*) FROM NumberedTables) THEN ''
ELSE ' UNION ALL '
END
FROM NumberedTables
ORDER BY TABLE_NAME

-- PRINT @SQL;
EXEC (@SQL);

This may get you out of a hole for now, but fixing the normalization is the way to go.
Post #1356703
Posted Monday, September 10, 2012 7:23 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Monday, August 25, 2014 7:14 AM
Points: 7,197, Visits: 6,341
aaron.reese (9/10/2012)
the view with UNION ALL the same query once for each agent table


Not something I recommend. The view will have to be recreated every time a new agents table is added, and it can break if the schema on any of the underlying tables is altered (except if WITH SCHEMABINDING is used, and that introduces its own issues).

Plus the more UNIONs get added to a query, the worse the performance becomes. It gets really messy really quickly.


Brandie Tarvin, MCITP Database Administrator

Webpage: http://www.BrandieTarvin.net
LiveJournal Blog: http://brandietarvin.livejournal.com/
On LinkedIn!, Google+, and Twitter.

Freelance Writer: Shadowrun
Latchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.
Post #1356719
Posted Monday, September 10, 2012 7:30 AM
Old Hand

Old HandOld HandOld HandOld HandOld HandOld HandOld HandOld Hand

Group: General Forum Members
Last Login: Wednesday, July 30, 2014 10:34 AM
Points: 386, Visits: 624
couldn't agree more!

Post #1356725
Posted Tuesday, September 11, 2012 7:43 AM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Today @ 6:23 AM
Points: 1,945, Visits: 2,922
I have a database that contains a number of individual tables for each sales agents.


This design flaw is called attribute splitting. Would you have “Male_Personnel” and “Female_Personnel” tables or a single “Personnel” table? Pretty obvious, isn't it? As you just figured out, you will always be repairing this insanity with UNION ALL statements that have to be re-written every time a new employee is added.

Any help would be greatly appreciated.


Now, you need to find the moron that did this to you and run him over in the parking lot. And finally, rewrite all of his code. That Agents is also a disaster. This is full of uselessly vague data element names. Record_type? This better not be meta data in RDBMS. Oh, minimal Netiquette is to post actual DDL and not narrative lists.

There is an Jewish joke in the garment district of New York City about "Levine the Tailor" who sells a guy a horrible suit. But if the buyer holds one pant leg up with his left hand, tilts his head, lifts a shoulder, etc. it will sort of fit.

The guy does not like contorting himself like this, so Levine tells him to walk to the end of the block and if he does not get one compliment, the suit is free. With nothing to lose, he does it.

When he gets to the corner, an old lady asks him "That is a great suit! Whose your tailor?"

"Levine, in the middle of the block. Why did you ask?"

The lady replies, "I don't mean to offend you, but if he can fit a suit to hopelessly deformed cripple like you, he can do anything with a suit!"




Books in Celko Series for Morgan-Kaufmann Publishing
Analytics and OLAP in SQL
Data and Databases: Concepts in Practice
Data, Measurements and Standards in SQL
SQL for Smarties
SQL Programming Style
SQL Puzzles and Answers
Thinking in Sets
Trees and Hierarchies in SQL
Post #1357406
Posted Tuesday, September 11, 2012 7:49 AM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Monday, August 25, 2014 7:14 AM
Points: 7,197, Visits: 6,341
Celko,

Cute joke.

Now do you actually have advice that is any different from that which was already offered?


Brandie Tarvin, MCITP Database Administrator

Webpage: http://www.BrandieTarvin.net
LiveJournal Blog: http://brandietarvin.livejournal.com/
On LinkedIn!, Google+, and Twitter.

Freelance Writer: Shadowrun
Latchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.
Post #1357418
Posted Tuesday, September 11, 2012 7:50 AM


SSC-Insane

SSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-Insane

Group: General Forum Members
Last Login: Today @ 12:11 PM
Points: 23,296, Visits: 32,034
CELKO (9/11/2012)
[quote]Comments deleted.


Really Mr. Celko? Your entire post is inappropriate, rude, and unprofessional. I personally would like to see you just leave this site and not come back.



Lynn Pettis

For better assistance in answering your questions, click here
For tips to get better help with Performance Problems, click here
For Running Totals and its variations, click here or when working with partitioned tables
For more about Tally Tables, click here
For more about Cross Tabs and Pivots, click here and here
Managing Transaction Logs

SQL Musings from the Desert Fountain Valley SQL (My Mirror Blog)
Post #1357420
« Prev Topic | Next Topic »

Add to briefcase 12»»

Permissions Expand / Collapse