简体   繁体   中英

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

How do I pass it in as 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 ?

尝试这个:

param.Value = testresults.Result==0?DBNull.Value:(object)testresults.Result;

Use param.Value = DBNull.Value; to set the value in database to NULL.

As you have defined your @Result parameter with default value null, so if you just dont pass this param it will take 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:

cmd.Parameters.AddWithValue("@Result", testresults.Result);

If Result is null , then the parameter is omitted and the default value 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