1

I have a stored procedure that returns a result, let's say it return rows of products. But each product status is not in our hand(can't get it). Our DBA just gave us another stored procedure to get the status of a product. We need to get individual product status by calling their SP. Let's say we have Product table,

CREATE TABLE PRODUCTS
(
   ID INT,
   Name NVARCHAR(100)
)

CREATE PROCEDURE GetProducts
AS
BEGIN
      INSERT INTO #TEMPTABLE
       SELECT * FROM PRODUCTS; -- Yes Too Much simplified

      -- Create cursor and set additional status in #TEMPTABLE

END;

EXEC GetStatus @ProductId; -- SP That need to get status

The problem is that GetStatus is only way to get the status and this sp sometimes return 2 columns, sometimes 4 and sometimes 8. The return columns will always include Status column for sure.

If columns names is fixed then there is no problem. Is there is a way to create dynamic table at the time of executing SP.

Tried this but not working,

WITH DynamicTable AS
(
    EXEC GetStatus
)
Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

1 Answers1

3

The answer to your question is no. There is no good way to get the value of a specific column returned by a stored procedure that can return a dynamic set of columns.

I say no "good" way, because of course there's a WAY. You can write an INSERT EXEC statement for every possible set of columns that the procedure can return and wrap each one in a TRY..CATCH block. If the first one errors, try the next one. As soon as you hit one that doesn't error, get the Status from it, and skip the rest.

That's the answer to your question. The solution to your problem, however, is to replace the GetStatus stored procedure with a Table-valued function. Then you can select from it, join to it, etc. I think the function would have to always return a consistent number of columns, but that would be better anyway, and the columns that aren't needed in a specific case could just be left empty or NULL.

Tab Alleman
  • 31,483
  • 7
  • 36
  • 52
  • I like the re-write to return the same number of columns a lot. If there is one shared column then we expect 12 columns in the new table (1+(2-1)+(4-1)+(8-1)) – Hogan Aug 05 '16 at 18:36
  • @Hogan (and Tab) Did SQL have a table type with dynamic columns. Like in dynamic languages Python, Js, C#(dynamic keyword), Ruby ? – Imran Qadir Baksh - Baloch Aug 05 '16 at 18:46
  • 1
    There's no way in SQL Server to declare a table type with dynamic columns, but you can declare it, and then ALTER it if circumstances require it. However, I don't know if you can ALTER the Table that is going to be output by a TVF, which why I say I *think* the function would have to have a consistent set of columns. – Tab Alleman Aug 05 '16 at 18:53
  • 2
    @user960567 - SQL was create over 50 years before any of those languages existed. There is no way to have "dynamic tables" in SQL. End of story. – Hogan Aug 05 '16 at 18:55