【发布时间】:2023-03-10 13:03:01
【问题描述】:
CREATE TABLE [dbo].[MyTable]([id] [int] IDENTITY(1,1) NOT NULL,
[MyNumericColumn] [decimal](18, 2) NOT NULL,[insert_time] [datetime] NOT NULL CONSTRAINT [DF__MyTable__insert___0F975522] DEFAULT (getdate()),
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED
([id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
GO
exec sp_executesql N'insert into MyTable ( MyNumericColumn, insert_time ) values ( @P0, getdate()),( @P1, getdate())',N'@P0 decimal(38,1),@P1 decimal(38,2)',10.0,0.99
exec sp_executesql N'insert into MyTable ( MyNumericColumn, insert_time ) values ( @P0, getdate()),( @P1, getdate()),( @P2, getdate()) ',N'@P0 decimal(38,2),@P1 decimal(38,1),@P2 decimal(38,3)',0.99,10.00,0.999
select * from [MyTable];
exec sp_executesql N'insert into MyTable ( MyNumericColumn, insert_time ) values( @P0, getdate()),( @P1, getdate()), ( @P2, getdate())',N'@P0 decimal(38,2),@P1 decimal(38,2),@P2 decimal(38,3)',0.99,10.00,0.999
select * from [MyTable];
而@P0 十进制(38,2),@P1 十进制(38,1),@P2 十进制(38,3) 为什么所有数据都是十进制(38,1)..
【问题讨论】:
-
在您用来生成这些语句的任何客户端结束时,您都可能成为数据类型推断的受害者。例如,所有 ADO.NET 客户端都将尝试仅根据参数值而不是语句来推断参数的类型。像
0.999这样的值将被推断为decimal(38, 3),因为这被认为是“安全”的精度,无论这最终在查询中是否有意义。在decimal的情况下,尤其是这可能会导致不直观或不正确的结果,这就是为什么您应该注意明确指定比例和精度的原因。 -
@JeroenMostert,也许AddWithValue 是罪魁祸首。
标签: sql-server tsql dynamic-sql