3

I have an sql pivot query which results in dynamic sql columns. How do I read these values into a C# object?

I haven't had much success while I am able to read values from the datareader. I am unable to pack it into an object.

I need to use datareader and pass an object through the service layer to the UI.

sql code similar to below,

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

SELECT @cols = STUFF((SELECT  ',' + QUOTENAME([MONTH]) 
                FROM #REVENUE
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

SELECT @query = 
'SELECT * FROM
(SELECT     
 [MONTH], 
SALES
FROM #REVENUE)X
PIVOT 
(
  AVG(SALES)
  for [MONTH] in (' + @cols + ')
) P

EXEC SP_EXECUTESQL @query
10
  • 1
    what you have tried so far? Commented Dec 7, 2015 at 5:17
  • Are all of the columns in the resultset named? If you use a function like COUNT(*) or possibly your pivot, the columns may not have a name. Ensure all the columns have a name which matches what you code expects. Commented Dec 7, 2015 at 5:18
  • able to read data but unable to proceed. as its dynamic i am stuck at the entity creation. Commented Dec 7, 2015 at 5:20
  • column names are dynamic vary like range of dates. Commented Dec 7, 2015 at 5:20
  • Please show us the query Commented Dec 7, 2015 at 5:25

1 Answer 1

2

If you select into a SQLDataReader, it has a GetName property which will return the column name. Something like:

    using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(yourQuery, yourConnection)) {

        using (IDataReader reader = cmd.ExecuteReader) {
            for (int i = 0; i <= reader.FieldCount; i++) {
                var name = reader.GetName(i);
            }
        }
}
Sign up to request clarification or add additional context in comments.

2 Comments

but what about the object / entity?
I'd properly just do a key/value store wrapped object - only other way I know (but haven't tried myself) would be ExpandoObject - msdn.microsoft.com/en-us/library/… - but it seems more trouble than it's worth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.