Repository navigation
Description
There appears to be some...glue...missing to allow streaming content into a table valued parameter. Consider the following extremely contrived scenario:
CREATE TABLE dbo.test (clob VARCHAR(MAX), blob VARBINARY(MAX));
CREATE TYPE dbo.test_tt AS TABLE(clob VARCHAR(MAX), blob VARBINARY(MAX));
// works...
using (var stream1 = IO.File.OpenRead("x:\\foo.bin"))
using (var stream2 = IO.File.OpenRead("x:\\bar.bin"))
using (var reader1 = IO.File.OpenText("x:\\foo.txt"))
using (var reader2 = IO.File.OpenText("x:\\bar.txt"))
{
var cmd1 = sqlconn.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "INSERT INTO dbo.test(clob, blob) VALUES (@pclob, @pblob);"
cmd1.Parameters.Add("@pblob", SqlDbType.VarBinary, -1);
cmd1.Parameters.Add("@pclob", SqlDbType.VarChar, -1);
cmd1.Parameters["@pblob"].Value = stream1;
cmd1.Parameters["@pclob"].Value = reader1;
cmd1.ExecuteNonQuery();
cmd1.Parameters["@pblob"].Value = stream2;
cmd1.Parameters["@pclob"].Value = reader2;
cmd1.ExecuteNonQuery();
}
// fails...
using (var stream1 = IO.File.OpenRead("x:\\foo.bin"))
using (var stream2 = IO.File.OpenRead("x:\\bar.bin"))
using (var reader1 = IO.File.OpenText("x:\\foo.txt"))
using (var reader2 = IO.File.OpenText("x:\\bar.txt"))
{
var meta = new[] {
new SqlMetaData("clob", SqlDbType.VarChar, -1),
new SqlMetaData("blob", SqlDbType.VarBinary, -1)
};
var records = new List<SqlDataRecord>();
records.Add(new SqlDataRecord(meta);
records.Add(new SqlDataRecord(meta);
records[0].SetValue(0, reader1);
records[0].SetValue(1, stream1);
records[1].SetValue(0, reader2);
records[1].SetValue(1, stream2);
var cmd2 = sqlconn.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "INSERT INTO dbo.test(clob, blob) SELECT clob, blob FROM @test_tt;"
var par = cmd2.Parameters.Add("@test_tt", SqlDbType.Structured, -1)'
par.TypeName = "dbo.test_tt";
par.Value = records;
cmd2.ExecuteNonQuery();
}
(Assuming I've written the example code above correctly, or at least its intent can be reasonably inferred), cmd1 should execute successfully twice, loading each row one-by-one. cmd2 will never run, as the calls to SqlDataRecord.SetValue don't accept either the Stream or TextReader objects, and throw an Invalid cast exception.
To that end, it does not appear that I can support both streaming multiple rows via TVP and streaming lobs via Stream and/or TextReader. I either have to load row-by-row (foregoing any decent set-based logic I might have in the SQL); or I have to load the whole content into memory (e.g. as String and Byte[]), to pass them. Neither approach seems particularly suitable for lots of input rows.
It's possible that Stream support might already come via SqlTypes.SqlBytes, which has a constructor which takes a Stream (I haven't tried); but the equivalent SqlTypes.SqlChars does not offer a constructor which takes TextReader. I'm not entirely convinced the SqlTypes don't automatically load the streamed data into contiguous memory, beforehand, anyway.
Is there anything specific preventing either SqlDataRecord accepting Stream and TextReader, or for SqlChars to accept TextReader, so there is at least some combination that would accept populating a TVP via entirely streamed data?
I suppose IDisposable lifetime has to be considered. Even though the above is contrived, I would expect that you would have to Close/Dispose each lob source only after each row was streamed in. I imagine normally streaming each row via a yield-based IEnumerable<SqlDataRecord> method, e.g.
private IEnumerable<SqlDataRecord> GetFileLobRecords()
{
var meta = new[] {
new SqlMetaData("clob", SqlDbType.VarChar, -1),
new SqlMetaData("blob", SqlDbType.VarBinary, -1)
};
var files = IO.Directory.EnumerateFiles("X:\\");
foreach (var f in files)
{
using (var s1 = IO.File.Open(f, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read))
using (var s2 = IO.File.Open(f, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read))
using (var t = new IO.StreamReader(s2))
{
var record = new SqlDataRecord(meta);
record.SetValue(0, t);
record.SetValue(0, s1);
yield return record;
}
}
}
...which, on the surface, at least looks like it would behave, with ExecuteNonQuery streaming each TVP row up to the server in turn, and then cleaning up the lob source after each row has been streamed.
(I note I haven't made any async considerations -- the old-style, non-async pattern is fine for my immediate needs, but others' expectations that it might also work in those situations as well may not be unreasonable).
Anyone with some deeper knowledge of the internals care to comment?
(Possibly related: #982)
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsInvestigating
Activity
johnnypham commentedon Jun 30, 2021
From what I've seen, the value of a SqlDataRecord column must be a compatible SQL DB type. I couldn't find a reason as to why that's the case. Maybe someone else can elaborate.
jimbobmcgee commentedon Jul 4, 2021
From my recent experience, I believe you can call
SqlDataRecord.SetValue()withSqlDbTypes and the reasonable native types (stringforSqlDbString, etc). It also allows anythingIConvertible, if it can be converted to the reasonable native type.For LOB types, SqlChars, SqlBytes, byte[], char[] and string seem to be the common types; and
SqlParameter.Valuecan also take a Stream (where CanRead is true) and a TextReader, butSqlDataRecord.SetValue()cannot.The perceived "contract" of
SqlDataRecord.SetValue()andSqlParameter.Valueare so close to each other -- both appear to make use of the same internal classes (StreamDataField, TextDataField) to handle reading the data -- so it feels like an oversight not to include support for Stream and TextReader in SqlDataRecord.cheenamalhotra commentedon Jul 7, 2021
@jimbobmcgee
Could you provide me complete repro in zip please? I'd like to test with some recent changes we are making internally.
jimbobmcgee commentedon Jul 8, 2021
@cheenamalhotra - I think the attached is self-contained and repeatable enough. It's written for LINQPad which is an interactive scratchpad for C# code, which lets me download the MDS package via NuGet. The principle should be sound in a csproj, but I don't have a working VS with .NET Core support at the moment.
It contains four tests, which are run against both System.Data.SqlClient and Microsoft.Data.SqlClient:
byte[]orstring)StreamorTextReader)IEnumerable<SqlDataRecord>, where eachSqlDataRecordis loaded from the in-memory typesIEnumerable<SqlDataRecord>, where eachSqlDataRecordis loaded from streamable typesConsts at the top of the LobStreamTest.linq file specify DB connection string and a local path for files to read. There's also a random seed, but it only keeps the binary/text content consistent across runs.
Interestingly, I notice that, when performing these tests against both
System.Data.SqlClientandMicrosoft.Data.SqlClient, MDS fails both my TVP tests (Test3 and Test4), while SDS only fails the streaming one (Test4). Is MDS using a differentSqlDataRecordto SDS?If I have done something wrong here, please advise.
cheenamalhotra commentedon Jul 26, 2021
Yes, MDS changed to Microsoft.Data.SqlClient.Server namespace from Microsoft.SqlServer.Server namespace for all applicable classes. Ref: Porting Cheat Sheet.
After changing to the new namespace I get only 4th test failing with MDS.
jimbobmcgee commentedon Jul 27, 2021
Thanks @cheenamalhotra, for the clarification regarding
SqlDataRecord. I actually still get a failure in Test 3, when usingMicrosoft.Data.SqlClient.Server.SqlDataRecord(i.e. find/replaces/Microsoft.SqlServer.Server/Microsoft.Data.SqlClient.Server/), but I haven't spent any real time diagnosing yet -- I'll check and come back.To be clear, though, some approach for making Test 4 work is the functionality I was looking for when I raised the issue. It should be possible to load a TVP containing
varbinary(max),varchar(max)ornvarchar(max), using anIEnumerable<SqlDataRecord>, without having to load the binary/string data into memory first.JRahnama commentedon Aug 5, 2021
Hi @jimbobmcgee,
Regarding Test3:
It is working fine. No exception captured. I got 6 rows affected by that test.
Test4:
The exception happens at
record.SetValue(0, bytes);Simply we cannot castStream/FileStreamtoVARBINARYas you have defined inMetaDataforthe SqlDataRecord. The approach should be the same as you have used fortextDataby using aStreamReader. BinaryReader could solve your issue.If I have managed to answer all your questions and there is nothing more to add to this thread please feel free to close the issue, otherwise if you are still getting failures with Test3 provide me the stack trace and exception message.
cheenamalhotra commentedon Jan 6, 2026
Closing as stale
jimbobmcgee commentedon Jan 7, 2026
@cheenamalhotra :: apologies for letting this one go (very) stale.
It still appears to be the case that it is not possible to populate a SqlDataRecord with either a TextReader or Stream and -- assuming I have not missed a method for doing so -- I perceive this to be an oversight in the overall API.
i.e. it should be functionally possible to pass either TextReader or Stream to the second parameter of
SqlDataRecord.SetValue(int, object), such that a table-type of VARBINARY(MAX) or VARCHAR(MAX) can be spooled, without requiring pre-loading into contiguous memory (via a string, char[] or byte[]).At first glance, the internals appear to be able to handle both types, either wrapped as a TextDataFeed, StreamDataFeed, but all the constructors/methods where one might create one of those wrappers are all marked internal.
(Similarly, it does not appear to be possible to create SqlBytes or SqlChars from either type -- constructors for these are also internal.)
The similar (in principle)
object SqlParameter.Valuesetter does not exhibit this restriction -- it accepts both TextReader and Stream and creates the relevant TextDataFeed or StreamDataFeed wrapper behind the scenes, using the internal methods.My suggestion (i.e. the reason for the issue) is that an equivalent behind-the-scenes conversion should also be possible when using
SqlDataRecord.SetValue(...).cheenamalhotra commentedon Jan 7, 2026
@jimbobmcgee I'm going to re-open to re-assess the scenario closely, as I believe streaming is supported for TVPs as per documentation: https://learn.microsoft.com/en-us/sql/connect/ado-net/sql/table-valued-parameters?view=sql-server-ver17#streaming-rows-with-a-datareader
However, I need to understand your case closely to respond better regarding SqlDataRecord API streaming support.
jimbobmcgee commentedon Jan 7, 2026
Thanks @cheenamalhotra.
I'll admit, I get a little lost when trying to follow the logic in Github/code-review alone, but I think the exception is thrown by
SqlDataRecord.SetValue()becauseMetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType()has no branch which explicitly matches types Stream or TextReader. By default, without a matching branch, this method returns the Invalid enum value, which results in the exception.That method would match on the internal StreamDataFeed or TextDataFeed wrapper types and return Stream or TextReader enum values as appropriate.
For SqlParameter, it appears objects passed to Value are first wrapped to the internal types using the static
SqlParameter.CoerceValue()function. For SqlDataRecord, this coercion is not done ahead of time, so the default Invalid result remains.If
SqlDataRecord.SetValue()did not throw at this point, it's next operation would be to call into a decorated chain ofValueUtilsSmi.SetCompatibleValue(...)which does have branches that deliberately handle DataFeed-derived types and does have setters to explicitly deal with Stream and TextReader.I lose track after reviewing after that, so I can't tell if there is a legitimate reason why the same branches cannot reasonably be followed in both SqlParameter and SqlDataRecord cases.
(That said, I also can't work out whether the existing API actually streams in the first place, or whether it later turns everything into a contiguous array or string anyway. If it does materialise the stream before sending it onto the server, then the whole purpose of streaming LOBs is somewhat lost, and this issue becomes moot.)
priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
Area\Sql Bulk Copy(closest match — TVP/SqlDataRecord streaming; no dedicated TVP label exists)Analysis
The reporter demonstrates that
SqlDataRecord.SetValue()cannot accept aStreamorTextReaderfor LOB columns (VARCHAR(MAX)/VARBINARY(MAX)) when populating a table-valued parameter (TVP) row-by-row, whereasSqlParameter.Valuesupports both via internalStreamDataFeed/TextDataFeedwrapping (throughSqlParameter.CoerceValue()). This forces callers to fully materialize LOB content intostring/byte[]before adding rows to a TVPIEnumerable<SqlDataRecord>, defeating the purpose of streaming for large object data. Root cause appears to be thatMetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType()has no branch recognizingStream/TextReadertypes the waySqlParameter's coercion path does. This is a legitimate API/feature gap (not a crash or data-corruption bug), affecting theMicrosoft.Data.SqlClient.Server.SqlDataRecordTVP streaming path. Severity: P3 (feature enhancement / API completeness — long-standing, no urgent regression, but has multi-year community interest).Next Steps
MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbTypeand the missingCoerceValue-equivalent step forSqlDataRecord), recommend assigning to Copilot coding agent to investigate addingStream/TextReadersupport toSqlDataRecord.SetValue()/SetBytes()/SetChars()(or equivalent), mirroring the coercion behavior inSqlParameter.CoerceValue(), and updateMetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType()to recognize these types.Microsoft.Data.SqlClient.Server.SqlDataRecord(MDS) and any shared TDS streaming (StreamDataFeed/TextDataFeed) code paths are covered by new unit/manual tests validating true streaming (not full in-memory materialization) for both sync and async TVP execution.