Supposedly I have a table called Person defined like this:
CREATE TABLE Persons
(
P_Id uniqueidentifier Default newsequentialid() NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)
How can I remove the default value for that column using an sql query? Furthermore how can I add it if it is not present to begin with.
I know it is possible to add it via altering the table and adding a constraint over the P_Id column but I am not sure if that is the only way. I have come across this article however what is suggested there doesn’t seem to really work.
Any ideas?
In SQL Server, defaults are defined as constraints associated with a specific column in a table. All constraints are assigned a name; this is important, because once the constraint is created, if you want to modify it you have to reference it by this name. (And I’ll be watching this question, to see if I’m wrong.)
Based on this sample table:
Step 1: Determine if a constraint exists on a column. Several ways to do this, all involving system views and/or metadata functions. Here’s a quick one, where ‘MyTable’ and ‘SomeData’ could be set as parameters:
Try it, and you’ll see that the name generated is essentially random blather. To determine if a default exists on a column, you could do:
To drop an existing default where you don’t know the name, you’ll have to build dynamic SQL. (that code in the referenced article is wrong, and clearly never tested.) @Călin does it slightly differently than I’d do it, but the idea’s the same:
(With error checking, parameters for the table and and column being checked, and so on.)
Lastly, you can avoid most of this by naming the defaults when you create the constraint, like so:
Or like so: