Often we need to add a non-nullable column to a table, and it is quite a mission. Using a default constraint as is doesn’t work, so we have to create nullable columns, update them to default values, then make them non-nullable. Is there not an easier way to do this?
Yes, the WITH VALUES modifier to a DEFAULT constraint applies the default value to existing rows, eliminating all the 'hard' work described in the question.
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id=OBJECT_ID('[caConfig]') AND [Name]='ExportWizardVersion')
ALTER TABLE [caConfig]
ADD
[ExportWizardVersion] varchar(5) not null CONSTRAINT DF_caConfig_ExportWizardVersion DEFAULT '5.8' WITH VALUES,
[ExportPeriodEnd] varchar(10) not null CONSTRAINT DF_caConfig_ExportPeriodEnd DEFAULT 'MonthEnd' WITH VALUES
Related
I have to add a column called 'Guid' that should be have default value. It's not primary-key.
So, I did it as below:
ALTER TABLE myTable ADD [Guid] uniqueidentifier NOT NULL DEFAULT(NewId())
Ok, now I have a column that has acceptable value. But after insertion a new row, the Guid column's value is
00000000-0000-0000-0000-000000000000
I tested it with another name:
ALTER TABLE MyTable ADD Guids uniqueidentifier NOT NULL DEFAULT(NewId())
and there is no problem with this. It seems that the main problem is the name of column (Guid), maybe. Is that true?
So, How can I fix that, since I can't use another name for it.
I want to add a Column to a table in my Database. As several data already exist in that particular table , MSSQL does not allow me to add a not Null field. So I can use a default keyword to solve this problem and run the below mentioned Query -
Alter table ServiceDetails
Add OCF_Internal_ID varchar(50) not null default 'OCF';
But now I want to make the "OCF_Internal_ID" field Primary key and I need to insert unique values to the every record of that particular filed. Please give me any suggestion.
How can I add Unique values to all the existing records ?
You can use one of these options
Alter table ServiceDetails
Add OCF_Internal_ID integer NOT NULL IDENTITY (1,1);
OR
Alter table ServiceDetails
Add OCF_Internal_ID uniqueidentifier NOT NULL default newid();
Then run this do define a primary key constraint
ALTER TABLE ServiceDetails
ADD CONSTRAINT PK_ServiceDetails_OCF_Internal_ID PRIMARY KEY CLUSTERED (OCF_Internal_ID);
GO
I am adding a new column in an existing table with preloaded data. This column uses a primary key from another table and I want to default this to 5. I have tried the following code:
ALTER TABLE group
ADD group_type INT
GO
ALTER TABLE group
ADD CONSTRAINT FK_group_type DEFAULT 5 FOR group_type
GO
I was expecting on alter of the group table then all the values will be filled with 5 but instead its NULL. What am I doing wrong?
First of all, adding a DEFAULT constraint (in it's own SQL statement) to a column does not effect existing data in that column. It only effects new INSERTS to that table which do not provide a value for that column.
Second, you haven't created a FOREIGN KEY constraint here.
EDIT:
Here would be one way to create the FK correctly
ALTER TABLE group
ADD group_type_id INT
GO
ALTER TABLE group
ADD CONSTRAINT fk_groupType FOREIGN KEY (group_type_id)
REFERENCES group_type (group_type_id)
This worked for me, it set the foreign key constraint, default value, and updated existing table records all in a single ALTER TABLE statement. I'm using a SQL Azure database (via SQL Management Studio), so, YMMV.
ALTER TABLE Group
ADD GroupTypeId int NOT NULL
CONSTRAINT DK_GroupTypeId DEFAULT (5) WITH VALUES
CONSTRAINT FK_GroupTypeId FOREIGN KEY
REFERENCES [dbo].[GroupType] (GroupTypeId)
GO
It took a while to run, but a subsequent select, showed the rows had the correct default value for those columns.
Disclaimer: I edited the above query from my table / key names to yours without re-testing it, so you may want to double check it for any typos or other mismatches; The syntax should be the same though.
You can use:
alter table [group]
add group_type int constraint df_group_type default (5) with values
However, it doesn't seem a good idea to use constant as a default value for a column, which is supposed to be FK column.
It seems, that may be what actually you are trying to do is following:
alter table [group] add column group_type int
GO
update [group] set group_type = (select id from group_type where desc ='typeA')
GO
alter table [group] add constraint FK_group_grouptype foreign key (group_type) references group_type (id)
GO
Adding default constraint will affect existing rows if you add new not nullable column to table.
ALTER TABLE group
ADD group_type INT NOT NULL
CONSTRAINT DK_group_type DEFAULT 5
GO
I have a table created like this originally:
CREATE TABLE dbo.XX (
YY int DEFAULT(NULL)
)
If you do this, and then script the table later on, you will get the following code, plus a randomly named default constraint:
CREATE TABLE [dbo].XX([YY] [int] NULL)
GO
ALTER TABLE [dbo].XX ADD DEFAULT (NULL) FOR [YY]
GO
Now is there any real point in specifying DEFAULT (NULL) on a column instead of just leaving it as [YY] [int] NULL in the first place?
There is no need to add a DEFAULT(NULL) to nullable columns.
If data is not supplied to such columns, they will have a NULL.
The only benefit I see is the one Larry Lustig has posted in his comment to the question - it documents the fact that you have not forgotten to add a default to the nullable column.
None that I can think of.
From a programming point of view NULL is the implicit default anyway without needing to (implicitly) create an actual default constraint in sys.objects.
Both of the following will end up inserting NULL without the default constraint.
INSERT INTO [dbo].XX([YY]) VALUES (DEFAULT)
INSERT INTO [dbo].XX([YY]) DEFAULT VALUES
I don't subscribe to the view in the comments that it documents you didn't "forget" to add a default constraint. Nullable columns rarely have default constraints in my experience so this would just add a load of unneeded clutter.
The more important thing to include is the column nullability - as below - so it is clear to future readers that the column is nullable and so it doesn't depend on ANSI_NULL_DFLT session options what you actually end up with.
CREATE TABLE dbo.XX (
YY int NULL
)
In SQL Server 2000/2005,
Is it possible to force the default value to be written to already existing rows when adding a new column to a table without using NOT NULL on the new column?
You need two statements. First create the column with not null. Then change the not null constraint to nullable
alter table mytable add mycolumn varchar(10) not null default ('a value')
alter table mytable alter column mycolumn varchar(10) null
I understand your question, but you are saying that for future records, NULL (unknown, indeterminate or whatever your semantics are) is acceptable (but if it is left off in an insert, there will be a default), but that for all the existing data, you are going to go ahead and assign it the default.
I would have to look hard at this situation and ask why you are even going to allow NULLs in future records at all - given none of the historical records will have it, and there is a default in place for future records.
I doubt it.
http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx
The approach recommended by Microsoft is as follows (taken from the url above)
UPDATE MyTable SET NullCol = N'some_value' WHERE NullCol IS NULL
ALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
[**WITH VALUES]**
WITH VALUES can be used to store the default value in the new column for each existing row in the table.
more detail on MSDN link .
https://msdn.microsoft.com/en-in/library/ms190273.aspx