0

I am trying to add default value to an existing table, but it is not working at all. I am expecting to see 'NO' when I add data in my table but it is not happening. I am not sure what is going on or if my syntax is wrong here. Please help. Thanks

ALTER TABLE [myTable] 
ADD CONSTRAINT [DF_myTable_FLAG] DEFAULT ('NO') FOR [FLAG]

The datatype for this column is varchar.

marc_s
759k185 gold badges1.4k silver badges1.5k bronze badges
asked Feb 11, 2014 at 21:39
2
  • 4
    Can you show us the insert statement you're using to insert a row? Commented Feb 11, 2014 at 21:42
  • 1
    First of all, this only applies to new rows being added, and it only works if you don't explicitly specify a value for that column in your INSERT statement. The syntax looks fine - but how are you inserting your new rows? Commented Feb 11, 2014 at 22:04

1 Answer 1

3

Only new records will get the default.

Test this:

CREATE TABLE #TEST(NAME VARCHAR(5), FLAG VARCHAR(3))
INSERT INTO #TEST (NAME) SELECT 'DAVE'
ALTER TABLE #TEST ADD CONSTRAINT [DF_TEST_FLAG] DEFAULT ('NO') FOR [FLAG]
INSERT INTO #TEST (NAME) SELECT 'MOE'
SELECT * FROM #TEST

Old records must be manually updated.

answered Feb 11, 2014 at 21:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.