
Dynamic SQL generation in T-SQL
If you don't have a working solution yet, try this one. It could be made
into a stored procedure very easily. I won't explain much about it unless
you need me to, because it is commented inside the code.
-- CODE BEGIN --
each table be seperated by exactly 1 comma and no spaces, it could be
modified to suit other needs though
required otherwise it will run together with the table name
to change this to just: " UNION "
anything is still null
-- the list contains at least one delimiter --> at least 2 tables are
supplied
BEGIN
-- if this is not the first table
-- add the UNION statement
-- parse next table from the list and add it to the select statement
-- find the position of the next delimiter, and save the position of the
last one
-- if no more delimiters found, then
BEGIN
-- add the UNION statement
-- parse the last table from the list and add it to the select statement
END
END
ELSE
-- the list contains at no delimiters --> only 1 table is supplied
-- for debugging only; uncomment to view the sql statement
-- execute the dynamic statement
-- CODE END --