I have a stored procedure that currently uses one CTE. This one works like so:
WITH MY_CTE AS
(
// Logic here uses SELECT * from a single table.
)
SELECT *
INTO #Tasks
FROM MY_CTE;
I now have a requirement to optionally call another CTE that will add more data to the original temp table. I was hoping to do something like this:
IF @Option = 1
BEGIN
INSERT INTO #Tasks
(
WITH MY_OTHER_CTE
(
// Logic here uses SELECT * from same table as first CTE.
)
SELECT *
FROM MY_OTHER_CTE
)
END
The problem is that the INSERT INTO #Tasks call requires specifying VALUES columns. Both CTE’s return records from the same table. The good benefit of original stored procedure was that it would work even if columns in that table changed, since I was using SELECT *. I could specify the columns knowing what they are in the shared table, but I lose that benefit (which in this specific case is an extremely useful benefit). Is there a way to accomplish what I’m trying to do, knowing that they are both selecting from the same table and that the columns will always match?
Does this work?
You might have another challenge if the table you’re selecting from (and hence the temp table) has an identity column