Skip to content

Cannot send DateOnly instance as a SqlDbType.Variant-typed parameter #3953

@edwardneal

Description

@edwardneal

Describe the bug

Discovered while trying to reproduce #3934. This only applies to netcore, due to the reliance upon the DateOnly type.

SqlClient cannot send a parameter of type sql_variant to SQL Server if that parameter's value is a DateOnly instance. The code paths which handle this in TdsParser (WriteSqlVariantValue and WriteSqlVariantDataRowValue) don't account for a TDS type of TdsEnums.SQLDATE.

In debug configuration, the code path hits an assertion. In release configuration, SqlClient will send the sql_variant header and not the data; as a result, SQL Server will notify SqlClient of a corrupted TDS stream and terminate the connection. The precise exception message is "The incoming tabular data stream (TDS) protocol stream is incorrect. The stream ended unexpectedly."

To reproduce

This replicates the error with the simple case (a scalar SqlParameter of SqlDbType Variant with a DateOnly value.)

using SqlConnection connection = new(DataTestUtility.TCPConnectionString);
connection.Open();
using SqlCommand cmd = new("SELECT @Param1", connection);
cmd.Parameters.AddWithValue("@Param1", DateOnly.MinValue).SqlDbType = System.Data.SqlDbType.Variant;
cmd.ExecuteNonQuery();

Expected behavior

I expect the query to execute successfully.

Further technical details

Microsoft.Data.SqlClient version: 7.0.0-dev (main branch), 6.1.4, 6.0.5, 5.1.9
.NET target: net8.0, net9.0, net10.0
SQL Server version: SQL Server 2022 and SQL Server 2025
Operating system: Windows 11

Additional context
I'm planning to fix this - raising the bug in advance of the PR to separate the problem from the investigation in #3934.

The existing test coverage for this is part of TvpTest - specifically, DateTimeVariantTest. This will complicate the merge slightly - I'm planning to cherry-pick a4e3a9c and a1e26b2 from dev/mdaigle/split-tvp-tests and build my extra validation on top of that.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions