我们正在使用.net Framework 4.7.2。我们将用户定义类型变量作为唯一参数的sp。
CREATE TYPE [dbo].[ABC] AS TABLE(
[A] [int] NOT NULL,
[B] [datetime] NOT NULL,
[C] [datetime] NOT NULL,
[Value] [decimal](19, 6) NULL)
对应的存储过程是
CREATE PROCEDURE [dbo].[myUSP]
@data dbo.ABC readonly AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM @data)
BEGIN
INSERT INTO dbo.MyTable
SELECT A, B, C, [Value] FROM @data;
END END
我的.Net代码是
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand insertCmd = new SqlCommand("dbo.myUSP", con))
{
con.Open();
using (transaction = con.BeginTransaction(IsolationLevel.RepeatableRead))
{
insertCmd.Transaction = transaction;
insertCmd.CommandType = CommandType.StoredProcedure;
try
{
SqlParameter parameter1 = insertCmd.Parameters.AddWithValue("@data", CreateSqlRecord(insert));
parameter1.SqlDbType = SqlDbType.Structured;
parameter1.TypeName = "dbo.ABC";
insertCmd.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
}
}
}
}
private IEnumerable<SqlDataRecord> CreateSqlRecord(IEnumerable<DataElementInput> entities)
{
SqlMetaData[] metaData = new SqlMetaData[4];
metaData[0] = new SqlMetaData("A", SqlDbType.Int);
metaData[1] = new SqlMetaData("B", SqlDbType.DateTime);
metaData[2] = new SqlMetaData("C", SqlDbType.DateTime);
metaData[3] = new SqlMetaData("Value", SqlDbType.Decimal);
SqlDataRecord record = new SqlDataRecord(metaData);
foreach (Model myModel in entities)
{
record.SetInt32(0, myModel .A);
record.SetDateTime(1,myModel.B);
record.SetDateTime(2, myModel.C);
record.SetDecimal(3, (Decimal)myModel.Value);
yield return record;
}
}
在将参数1传递给SQLConnection并使用ExecuteNonQuery执行之前,我检查了它的值,它正确包含十进制值。 另一方面,我还检查了直接从SQL Server Management Studio运行我的sp,它在表dbo.MyTable中插入正确的十进制值。
BEGIN DECLARE @data dbo.ElementFactData;INSERT @data (ElementId,StartDateTime, EndDateTime, Value) VALUES( 1002, '1/1/1800' , '1/1/1900' , 0.786); exec dbo.myUSP @data;END
但是,当我尝试从.net代码插入记录时,小于0.5的十进制值变为0,大于0.5的值变为1。例如4.2变为4,5.87变为6
.net代码有什么问题吗?
答案 0 :(得分:2)
我猜
metaData[3] = new SqlMetaData("Value", SqlDbType.Decimal);
需要指定的精度和小数位数。 看起来像这样:
metaData[3] = new SqlMetaData("Value", SqlDbType.Decimal, 19, 6);
您的CreateSqlRecord方法应如下所示:
private IEnumerable<SqlDataRecord> CreateSqlRecord(IEnumerable<DataElementInput> entities)
{
SqlMetaData[] metaData = new SqlMetaData[4];
metaData[0] = new SqlMetaData("A", SqlDbType.Int);
metaData[1] = new SqlMetaData("B", SqlDbType.DateTime);
metaData[2] = new SqlMetaData("C", SqlDbType.DateTime);
metaData[3] = new SqlMetaData("Value", SqlDbType.Decimal, 19, 6);
SqlDataRecord record = new SqlDataRecord(metaData);
foreach (Model myModel in entities)
{
record.SetInt32(0, myModel .A);
record.SetDateTime(1,myModel.B);
record.SetDateTime(2, myModel.C);
record.SetDecimal(3, (Decimal)myModel.Value);
yield return record;
}
}