[英]How do you pass null values for dbtype decimal??
I am passing a parameter into a stored procedure: 我正在将参数传递给存储过程:
param = CreateInParameter("Result", DbType.Decimal);
param.Value = testresults.Result;
cmd.Parameters.Add(param);
sometimes testresults.Result
will be null 有时是
testresults.Result
将为null
How do I pass it in as NULL? 如何将其作为NULL传递?
Here's my stored proc: 这是我存储的过程:
USE [SalesDWH]
GO
/****** Object: StoredProcedure [dbo].[Insert_TestResults] Script Date: 12/25/2011 23:49:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[Insert_TestResults]
-- Add the parameters for the stored procedure here
@TestName varchar (500),
@Result decimal (18,4)=null,
@NonNumericResult varchar (50)=null,
@QuickLabDumpid int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
INSERT INTO [SalesDWH].[dbo].[TestResults]
([TestName]
,[Result]
,nonnumericresult
,[QuickLabDumpid])
VALUES
(@TestName,@Result,@nonnumericresult,@QuickLabDumpID)
END
If testresults.Result
was not assigned a value, it just goes in as 0. How do I allow it to go into the database as NULL
? 如果没有为
testresults.Result
赋值,则它只会以0的形式输入。如何允许它以NULL
进入数据库?
尝试这个:
param.Value = testresults.Result==0?DBNull.Value:(object)testresults.Result;
Use param.Value = DBNull.Value;
使用
param.Value = DBNull.Value;
to set the value in database to NULL. 将数据库中的值设置为NULL。
As you have defined your @Result parameter with default value null, so if you just dont pass this param it will take null. 由于您定义的@Result参数的默认值为null,因此,如果不传递此参数,则它将为null。
if(testresults.Result>0) {param = CreateInParameter("Result", DbType.Decimal); param.Value = testresults.Result; cmd.Parameters.Add(param); }
Have the stored proc default the parameter to null (as you've done), then: 使存储的proc默认将参数设置为null(如您所愿),然后:
cmd.Parameters.AddWithValue("@Result", testresults.Result);
If Result
is null
, then the parameter is omitted and the default value is used. 如果
Result
为null
,则省略参数,并使用默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.