1

Here is my query, it is on 2014 Adventure works.

DECLARE @l_RunSQL VARCHAR(MAX);

SELECT @l_RunSQL = COALESCE(@l_RunSQL + ' UNION ALL SELECT * FROM [', 'SELECT * FROM [') + TABLE_SCHEMA +'].['+ TABLE_NAME+']'
FROM INFORMATION_SCHEMA.TABLES
WHERE [TABLE_TYPE] = 'BASE TABLE'
  AND [TABLE_NAME] LIKE 'Address';

EXEC (@l_RunSQL)
    WITH RESULT SETS
         (
             (
                 [AddressID] [INT],
                 [AddressLine1] [NVARCHAR](60),
                 [AddressLine2] [NVARCHAR](60),
                 [City] [NVARCHAR](30),
                 [StateProvinceID] [INT],
                 [PostalCode] [NVARCHAR](15),
                 [SpatialLocation] [GEOGRAPHY],
                 [rowguid] [UNIQUEIDENTIFIER],
                 [ModifiedDate] [DATETIME]
             )
        );

I am able to run this in SSMS and I get the contents of the Person.Address table as desired.

In C#, I create a connection node and then a command node and try and execute query like so:

using (var reader = command.ExecuteReader(CommandBehavior.SchemaOnly))
{
     schemaTable = reader.GetSchemaTable();
}

And the reader results come back empty. Why is this command valid in SSMS but not using C# ?

The connection is of type System.Data.SqlClient.SqlConnection and the command is of type System.Data.SqlClient.SqlCommand.

Any help would be greatly appreciated

1 Answer 1

2

It's because you are executing with CommandBehavior.SchemaOnly, which returns column information only, without data, see documentation.

The query returns column information only. When using SchemaOnly, the .NET Framework Data Provider for SQL Server precedes the statement being executed with SET FMTONLY ON.

To access the returned data from the query, just execute as below.

using (var reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        // Access your data here
        Console.WriteLine(String.Format("{0}", reader[0])); // Column AddressID
        // ...
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

But shouldn't I at least be seeing my schema info, like what is in the result set?
Might have to do with the WITH RESULT SETS feature; with this in the query GetSchemaTable returns null. For a 'regular' query (eg. select * from sometable) CommandBehavior.SchemaOnly is OK to return the schematable. At least, without CommandBehavior.SchemaOnly you can access the schematable.

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.