Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
help me hows to insert default date in date_no column if date_no column getting null value through insert query using in C# program.??????
Posted
Comments
Maciej Los 29-Apr-13 2:46am    
Not clear! Please, be more specific and provide more details (example data).
ashu_dhiman 29-Apr-13 3:35am    
hello Maciej

i have table in database name data_details it has different column name as customer_name,cs_address,date_birth.
And i want to enter already set default value for date_birth column if i get null value during inserting the new record.
Maciej Los 29-Apr-13 3:43am    
What is your table definition?
What is your query for insert new record?
Prasad Khandekar 29-Apr-13 2:57am    
SQL Server Supports default values for columns via DEFAULT Constraints. For it to work your INSERT Query should omit the column. You can do this part in C#.
Maciej Los 29-Apr-13 3:44am    
My virtual 5!
Please, post it as an answer.

Let see the example:
SQL
DECLARE @dates TABLE(aDate DATETIME NULL)

DECLARE @myDate DATETIME

SET @myDate='2013-01-01'
INSERT INTO @dates (aDate)
VALUES(@myDate)

SET @myDate=NULL

INSERT INTO @dates (aDate)
VALUES(@myDate)


In above example, @dates table has defined aDate field which can store NULL values. So, when you try to add nullable values, table "accept" it.

Change the definition of your table to:
SQL
DECLARE @dates TABLE(aDate DATETIME NOT NULL)

and try to add NULL value.
What would happen? Error occurs:
Msg 515, Level 16, State 2, Line 12<br />
Cannot insert the value NULL into column 'aDate', table '@dates'; column does not allow nulls. INSERT fails.


If you want to add default date in case of NULL, create stored procedure like this:
SQL
CREATE PROCEDURE AddNewDefaultDate
    @myDate DATETIME NULL
BEGIN
    INSERT INTO YourTable (DateColumn, Column1, Column2, Column3,... ColumnN)
    VALUES(COALESCE(@myDate, '1900-01-01'), 'a', 1,... 3)
END
 
Share this answer
 
AS prasad sekhar said set DEFAULT constraint of your date_no column in table to the default value you want to save. do not insert the value to this column through insert query from your C# code. it will always insert the default value t this column whenever an insert operation is done on table.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900