How to insert NULL into database if form field is empty

前端 未结 7 777
花落未央
花落未央 2021-01-01 17:56

I have a form and stored procedure that inserts the data from the form. It works fine except that if a field isn\'t filled in it doesn\'t insert a NULL into SQL

7条回答
  •  执笔经年
    2021-01-01 18:41

    While creating stored procedure make those columns as null which can be null.. like

    CREATE PROCEDURE [dbo].[USP_TDS_SaveRecod]
    
    @ID INT,
    
    @CODE  INT,
    
    @FIRSTNAME VARCHAR(8)=NULL,
    
    @CITY VARCHAR(15)=NULL
    
    AS
    
    BEGIN
    
        .........................
    
        .........................
    
        .........................
    END
    

    and then in code don't add those parameters which are null..

    cmd.Parameters.Add("@ID", SqlDbType.Int).Value = obj.ID;
    cmd.Parameters.Add("@CODE", SqlDbType.Int).Value = obj.CODE;
    if(pd_first_name.Text != "")
    {
        cmd.Parameters.Add("@FIRSTNAME", SqlDbType.VarChar).Value = pd_first_name.Text;
    }
    if(city.Text != "")
    {
        cmd.Parameters.Add("@CITY", SqlDbType.VarChar).Value = pd_first_name.Text;
    }
    

提交回复
热议问题