1

I am adding a column as a foreign key which cannot be NULL and so need to have a DEFAULT value.

ALTER TABLE location
ADD [retailer_brand_id] INT NOT NULL DEFAULT (SELECT retailer_id from retailer),
FOREIGN KEY(retailer_brand_id) REFERENCES retailer_brand(retailer_brand_id);

What I want to achieve is, get the retailer_id from SELECT retailer_id from retailer and if it is equal to 12 then set it to 0, otherwise set to the retailer_id returned by the select query.

When I use the above query, I get an error message

Subqueries are not allowed in this context. Only scalar expressions are allowed.

2
  • 1
    Do not use defaulting there, just let the column to be created will NULL's and UPDATE the column later. Commented Aug 1, 2018 at 23:39
  • 1
    SELECT retailer_id from retailer is likely going to give you more than one Id (unless there's only one entry in the table at the time). I'm not sure there's a way to dynamically assign a default value. Commented Aug 1, 2018 at 23:41

2 Answers 2

1

I recommend a calculated column instead....so you don't also have to have this case statement in application logic as well as the table definition...don't want it in 2 spots...and don't have to worry about when retailerid changes...calc column would take care of that

Sign up to request clarification or add additional context in comments.

3 Comments

okay, I haven't used calculated columns before, can you provide a sample for my query?
which retailer are you pulling - SELECT retailer_id from retailer - most likely gives you one id...if you can resolve that piece...i can help you with the rest...there should be some type of link between your location data and what retailer you want?
I have retailer specific database so every SELECT retailer_id from retailer fetches precisely one record, and yes I get the required id of the retailer from one of the columns.
0

I needed similar functionality. Calculated column is not an option for me, since my value should be changeble later by user, so I went with trigger on insert.

Described for example here: Trigger to update table column after insert?

Comments

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.