2

These is my example table definition:

CREATE TABLE [MyTable] 
(
    [ColumnName] [bit] NOT NULL
)

ALTER TABLE [MyTable] ADD DEFAULT ((0)) FOR [ColumnName]

I want to be able to pass a Null value to my stored procedure's @ColumnValue, something like:

@ColumnValue = null;

INSERT INTO [MyTable] ([ColumnName])
VALUES (@ColumnValue)

But I'm getting this error:

"Cannot insert the value NULL into column... INSERT fails with"

Why the DEFAULT constraints not working?

1
  • 4
    The default value will be inserted if the requested insert doesn't specify a value for the field. You're specifying NULL for that field. If possible, modify your insert to exclude the field entirely, or modify the application doing the insert to be aware of and supply the default value. Commented Sep 24, 2017 at 6:01

2 Answers 2

3

Solved:

as @J.D. Pace said: The default value will be inserted only if the value is not specified on the Insert statement.

so as @dotNET suggested, i have specified the default value in the INSERT query statement using the ISNULL:

ISNULL - The SQL Server ISNULL() function lets you return an alternative value when an expression is NULL:

@ColumnValue = null;

INSERT INTO [MyTable] (
    [ColumnName]
)
VALUES (
    ISNULL(@ColumnValue, 0)
)
Sign up to request clarification or add additional context in comments.

Comments

1

A table with only one column of bit type with a default value seems to be a bad design. This stuff can almost certainly be stored in a different and better way. On the other hand, if there are other columns in the table that you didn't include in the post, just skip this particular column in your INSERT query and it will work fine. Lastly, you can specify the default value in your INSERT query too.

2 Comments

it is only example, I can't skip the column because it's value passed to my stored procedure's parameter
Can't you use an IF/ELSE in your SP, using two different queries in case the passed parameter is NULL or non-NULL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.