简体   繁体   中英

System.Data.SqlClient.SqlException: 'Operand type clash: datetime2 is incompatible with decimal

I have a Stored Procedure which requires a structured parameter. I'm trying to call the stored procedure from my C# code and I get following error.

System.Data.SqlClient.SqlException: 'Operand type clash: datetime2 is incompatible with decimal The data for table-valued parameter "@TableType" doesn't conform to the table type of the parameter. SQL Server error is: 200, state: 7'

Below is my stored procedure which is available in the database.

CREATE PROCEDURE dbo.spProcessData
    @TableType AS dbo.TblTypeHourlyData READONLY
AS
BEGIN
    SET NOCOUNT ON;


END

This is my table type script.

CREATE TYPE dbo.TblTypeHourlyData AS TABLE 
(
    Name NVARCHAR(50),
    RecordDate DATETIME,
    Amount  DECIMAL(18,2)
)
GO

I call the SP by passing the required parameter (data table). However, it returns an error in the var executeNonQuery = command.ExecuteNonQuery(); line.

        List<HourlyData> data = .................
        using (var connection = CreateConnection())
        {
            using (var command = connection.CreateCommand())
            {
                command.CommandText = "dbo.spProcessData";
                command.CommandType = CommandType.StoredProcedure;

                DataTable paramDT = new DataTable();
                using (var reader = ObjectReader.Create(data))
                {
                    paramDT.Load(reader);
                }

                var param1 = new SqlParameter("@TableType", SqlDbType.Structured)
                {
                    TypeName = "dbo.TblTypeHourlyData",
                    Value = paramDT
                };

                command.Parameters.Add(param1);
                connection.Open();
                var executeNonQuery = command.ExecuteNonQuery(); // ERROR
                connection.Close();

                var value = executeNonQuery > 0;
                return value;
            }
        }

For the "data" variable, I already have a data set. HourlyData class has the same structure as the table type.

public class HourlyData
{
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public DateTime? RecordDate{ get; set; }

        [DataMember]
        public decimal? Amount{ get; set; }
}

According to the info here you need to add an attribute so that the column order resulting from ObjectReader.Create(data) is the same as expected in the TVP.

If the attribute is not defined in the source class then alphabetical order is used

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM