i have a database table with a list of sql views
i want to create a new view or stored procedure that based on which views are in that table will return those views unioned
like this
SELECT ALINE1, HOME, EMAIL, EXPIRE, EDATE7, type
FROM dbo.campaign_membership_30
UNION ALL
SELECT ALINE1, HOME, EMAIL, EXPIRE, EDATE7, type
FROM dbo.campaign_membership_30n
UNION ALL
SELECT ALINE1, HOME, EMAIL, EXPIRE, EDATE7, type
FROM dbo.campaign_membership_60n
UNION ALL
SELECT ALINE1, HOME, EMAIL, EXPIRE, EDATE7, type
FROM dbo.campaign_membership_today
UNION ALL
SELECT ALINE1, BOOKNO, EMAIL, DEPART, DEP7, type
FROM dbo.depart_151days
UNION ALL
SELECT ALINE1, BOOKNO, EMAIL, DEPART, DEP7, type
FROM dbo.depart_90Days
There are a lot of major caveats here.
First, using dynamic SQL is often dangerous. It can open up your database to SQL injection attacks. If you don’t understand what these are then you need to do a lot of educating of yourself before I would suggest that you use dynamic SQL.
Second, this kind of a pattern (storing tables and columns in a table from which to generate SQL) is a really bad pattern. There are many problems with it. I can’t suggest alternative solutions though without knowing more about your application/problem space.
That said, the following is a simplistic version of how it might work in SQL Server 2005. This does not include error handling, etc.
The function Concatenated_Rows would have to be written. You could alternatively use a cursor or maybe even FOR XML to create the concatenated string. Here’s a link that does a good job explaining many of the possible methods and does a good job of comparing them.
Again, there are probably better solutions out there then going this route, especially if this is more than a one-off task.