I have the following stored procedure that generates SQL statements based on certain conditions.
I\'d like for the SQL statements to also return the actual results into a
Try this:
/* Execute the dynamic SQL to return their resultsets if cmd variable IS NOT NULL */
IF @ReportYearCmd IS NOT NULL
EXEC ( @ReportYearCmd );
IF @CosCountCmd IS NOT NULL
EXEC ( @CosCountCmd );
IF @FranchiseCountCmd IS NOT NULL
EXEC ( @FranchiseCountCmd );
IF @ProductCountCmd IS NOT NULL
EXEC ( @ProductCountCmd );
Note: This potentially returns four different resultsets--not a pivoted result.
EDIT:
Return a single resultset for each reject category.
This is about as close as you're going to get without having to do a lot of extra work:
DECLARE @Rejects TABLE (
[Report Year] VARCHAR(50),
[COS - Country Code] VARCHAR(50),
[Product - Style Code] VARCHAR(50),
[Franchise - Style Code] VARCHAR(50)
);
IF @ReportYearCmd IS NOT NULL
INSERT INTO @Rejects ( [Report Year] ) EXEC ( @ReportYearCmd );
IF @CosCountCmd IS NOT NULL
INSERT INTO @Rejects ( [COS - Country Code] ) EXEC ( @CosCountCmd );
IF @FranchiseCountCmd IS NOT NULL
INSERT INTO @Rejects ( [Franchise - Style Code] ) EXEC ( @FranchiseCountCmd );
IF @ProductCountCmd IS NOT NULL
INSERT INTO @Rejects ( [Product - Style Code] ) EXEC ( @ProductCountCmd );
-- Return resultset.
SELECT * FROM @Rejects;
Returns something like:
+-------------+--------------------+------------------------+----------------------+
| Report Year | COS - Country Code | Franchise - Style Code | Product - Style Code |
+-------------+--------------------+------------------------+----------------------+
| NULL | reject1 | NULL | NULL |
| NULL | reject2 | NULL | NULL |
| NULL | NULL | NULL | Rejectxy |
| NULL | NULL | NULL | Reject1234 |
| NULL | NULL | NULL | Reject567 |
+-------------+--------------------+------------------------+----------------------+
Your calling application will need to handle NULL values when processing the results as there is no easy way to "roll-up" NULL columns/rows to reduce the results as shown in your expectation.
) AS [ValidationCounts];
-- insertion here-
Insert into temp_table (col1, col2, col3, ...)
SELECT
@ReportYearCmd AS ReportYearCmd,
@CosCountCmd AS CosCountCmd,
@FranchiseCountCmd AS FranchiseCountCmd,
@ProductCountCmd AS ProductCountCmd;