Click here to Skip to main content
15,912,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm a newbie. I'm trying to learn default constraints.

I have created a table as below.

SQL
CREATE TABLE PERSONS1
(
Emp_ID int CONSTRAINT Constpk PRIMARY KEY,
Emp_Name varchar(40),
Emp_City varchar(20) DEFAULT 'Bangalore'
)



However, I'm unable to insert the values using the following codes.

SQL
INSERT INTO PERSONS1
VALUES ( 21, 'John',NULL)


NULL Value is updated in City column
OR

SQL
INSERT INTO PERSONS1
VALUES ( 212, 'John','')

No values in City column

OR

SQL
INSERT INTO PERSONS1
VALUES ( 213, 'John')


I get an error message for this.


Where am I going wrong? Please help me out!

I'm using sql server r2 2008

Thanks in advance!
Posted
Updated 5-Feb-13 0:10am
v2

The third is almost the right one, but since if you omit a field, you have to specify which are you passing.
SQL
INSERT INTO PERSONS1(Emp_ID, Emp_Name) VALUES ( 213, 'John')
 
Share this answer
 
v2
Comments
RedDk 5-Feb-13 13:04pm    
Credit where credit's due ...
Zoltán Zörgő 5-Feb-13 13:45pm    
Thank you.
try

SQL
INSERT INTO PERSONS1 (Emp_ID,Emp_Name)
VALUES ( 21, 'John');


Default constraint will come into play when you do not input any value via insert statement.

Also, hope the column Emp_Id is not an auto number column
 
Share this answer
 
The reason your first two queries fail to use the default value is because you explicitly set a value there. A default value is not used to replace a null value or empty string - it is there to put in a value when you don't supply one (this is not the same as explicitly choosing a null value).

The failure in your third example is because the INSERT expects three values and you only supply two. In cases like this, you have to set the columns you are expecting to insert into yourself like this
SQL
insert into persons1(emp_id, emp_name)
values (213, 'John')
Now, when you run that query, the database engine sees that you haven't supplied a value for Emp_City, so it will apply the default value of Bangalore.
 
Share this answer
 
Comments
Newbie271 5-Feb-13 6:16am    
Thanks!! :)
Pete O'Hanlon 5-Feb-13 8:26am    
You're welcome.

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