SQL Server 8111 - but column is NOT NULLABLE - sql-server

I want to add a primary key constraint to an existing column on an existing table that contains data. The column is not nullable.
However, when I call
alter table mytable add primary key (mycolumn)
I get an 8111:
Msg 8111, Level 16, State 1, Line 2 Cannot define PRIMARY KEY
constraint on nullable column in table 'mytable'
Even if I call both instructions in a row:
alter table mytable alter column mycolumn INT NOT NULL;
alter table mytable add primary key (mycolumn)
I still get an 8111
- and the column description in SQL Server Management Studio confirms, that mycolumn is set to NOT NULL
What can I do this?

You need to separate your batches. It would be best to include the schema name as well.
alter table dbo.mytable alter column mycolumn INT NOT NULL;
go
alter table dbo.mytable add primary key (mycolumn);
rextester demo: http://rextester.com/TZLEWP56616

Related

Column is not the same data type as referencing column

I'm altering table to add a foreign key as following:
ALTER TABLE [MS_Test].[dbo].[Studies]
ADD CONSTRAINT F_Id
FOREIGN KEY (Id) REFERENCES [M_Test].[dbo].[MS](Id);
I get the following error:
Msg 1778, Level 16, State 0, Line 2
Column 'MS_Test.dbo.FM.Id' is not the same data type as referencing column 'Studies.Id' in foreign key 'F_Id'.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint or index. See previous errors.
I have already a lot of data stored in my tables so I can't just drop table and create it again.
SQL has the following command:
ALTER TABLE [table] ALTER COLUMN [column] SET DATA TYPE [new data type]
EDIT
As you modified the question, it seems that you need to add a new column, instead of changing an existing one.
Try something like this:
ALTER TABLE [MS_Test].[dbo].[Studies]
ADD COLUMN MS_id {your [MS_Test].[dbo].[MS].Id column type};
ALTER TABLE [MS_Test].[dbo].[Studies]
ADD CONSTRAINT F_Id
FOREIGN KEY (MS_id) REFERENCES [M_Test].[dbo].[MS](Id);

Alter column length with or without data in table

Its about ORACLE (PL/SQL) script. I am not very familiar with databse to be honest.
I want to alter the length of a string in a column from 30 to 60. It is not null column.
If the table is empty and I run following script then it works:
alter table [TABLE_NAME] add ( NEW_COLUMN NVARCHAR2(60) DEFAULT 'null' NOT NULL );
/
alter table [TABLE_NAME] DROP CONSTRAINT PK_[TABLE_NAME];
/
begin
for rec in ( select * from [TABLE_NAME] )
loop
update [TABLE_NAME] set NEW_COLUMN =rec.OLD_COLUMN where Name_ID=rec.Name_ID;
end loop;
end;
/
alter table [TABLE_NAME] drop column OLD_COLUMN;
/
alter table [TABLE_NAME] rename column NEW_COLUMN to OLD_COLUMN;
/
alter table [TABLE_NAME] add CONSTRAINT PK_[TABLE_NAME] PRIMARY KEY(Name_ID);
/
But if the table has values then this script does not work.
It gives error: Cannot drop constraint - nonexistent constraint
However, if I remove lines about constraints (second and second last) then it works.
Now I don’t know if the table will be empty or it will have data so I need a script that can work in both the situations. Can anyone help please?
Following script for creating table:
CREATE TABLE TABLE_NAME
(
Name_ID NVARCHAR2(7) NOT NULL,
OLD_COLUMN NVARCHAR2(30) NOT NULL,
CONSTRAINT PK_TABLE_NAME PRIMARY KEY(Name_ID, OLD_COLUMN)
)
/
So while creating table it puts the primary key constraints but while updating table it drops this constraints somehow. I am simplyfying the sitation here. The tables are updates through java code. What I need to do is make a script that work in both situations - with data or just after creating table and modifying the column.
The following script works for me, regardless of whether the insert statement is present or not (ie. the table has or has not data):
CREATE TABLE TABLE_NAME
(
Name_ID NVARCHAR2(7) NOT NULL,
OLD_COLUMN NVARCHAR2(30) NOT NULL,
CONSTRAINT PK_TABLE_NAME PRIMARY KEY(Name_ID, OLD_COLUMN)
);
insert into table_name (name_id, old_column)
values ('test', 'test_old_col');
commit;
alter table table_name add (new_column nvarchar2(60) default 'null' not null);
update table_name set new_column = old_column;
commit;
alter table table_name drop constraint PK_TABLE_NAME;
alter table table_name drop column old_column;
alter table table_name rename column new_column to old_column;
alter table TABLE_NAME add CONSTRAINT PK_TABLE_NAME PRIMARY KEY(Name_ID, old_column);
drop table table_name;
I have assumed that you meant to recreate the primary key with the old_column in it, otherwise you would be unable to recreate it if there are any duplicate values present in the name_id column.
As an alternative, you can save the old data and create a new table with new parameters. Then insert the old values.
In SQL Server Management Studio:
"your database" => task => generatescripts => select specific database object => "your table" => advanced => types of data to script - schema and data => generate

How do I set default value for a foreign key column in sql server?

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

Change datatype of a column and set a column as identity in SQL

----------------------------------------------
DepartmentCode varchar(30) AllowNulls
----------------------------------------------
Does anyone know how to change the datatype of a column in SQL 2008? This is the column I want to alter but when I try this query,
ALTER TABLE SystemDepartment ALTER COLUMN DepartmentCode smallint NOT NULL
I get the following error:
Msg 5074, Level 16, State 1, Line 1
The object 'PK_SystemDepartment' is dependent on column
'DepartmentCode'. Msg 4922, Level 16, State 9, Line 1 ALTER TABLE
ALTER COLUMN DepartmentCode failed because one or more objects access
this column.
My question is how to force my query to cope with it? and I also would like to set this column as primary key and identity
You will first need to drop Primary Key constraint.
ALTER TABLE SystemDepartment DROP CONSTRAINT PK_SYSTEMDEPARTMENT
Then only you can ALTER that column.
You can not force existing column to identity. In this case you will need to add new column with identity and then do sp_rename to old name.
If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:
ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]
For more info see the comments by the brilliant Aaron Bertrant on this answer.
Try this ,
as you told you are getting primary key constraint error , 1st you have to drop the primary key and use the following query ,
ALTER TABLE SystemDepartment MODIFY DepartmentCode int(3)
Thanks,
Venkat.

Add primary key column in SQL table

I am student of RDBMS.
I have very basic question let say I have one existing Table in SQL server. What will be script to alter table.
Drop Column 'RowId' if exist.
Drop contraint if exist.
Add one new column 'RowId' into table.
Make this column as primary key.
Autoincrement type int.
In SQL Server 2005 or newer, you could use this script:
-- drop PK constraint if it exists
IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.YourTable') AND Name = 'PK_YourTable')
ALTER TABLE dbo.YourTable
DROP CONSTRAINT PK_YourTable
GO
-- drop column if it already exists
IF EXISTS (SELECT * FROM sys.columns WHERE Name = 'RowId' AND object_id = OBJECT_ID('dbo.YourTable'))
ALTER TABLE dbo.YourTable DROP COLUMN RowId
GO
-- add new "RowId" column, make it IDENTITY (= auto-incrementing)
ALTER TABLE dbo.YourTable
ADD RowId INT IDENTITY(1,1)
GO
-- add new primary key constraint on new column
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable
PRIMARY KEY CLUSTERED (RowId)
GO
Of course, this script may still fail, if other tables are referencing this dbo.YourTable using foreign key constraints onto the pre-existing RowId column...
Update: and of course, anywhere I use dbo.YourTable or PK_YourTable, you have to replace those placeholder with the actual table / constraint names from your own database (you didn't mention what they were, in your question.....)
Note: this answer was added before questions update
Add new column (note: you can only have one IDENTITY column per table)
Drop old primary key
Add new primary key
Drop old column if needed
Sample script:
CREATE TABLE whatever (
OldPKColumn uniqueidentifier NOT NULL,
CONSTRAINT PK_whatever PRIMARY KEY (OldPKColumn)
)
ALTER TABLE whatever
ADD RowId int NOT NULL IDENTITY (1,1);
ALTER TABLE whatever
DROP CONSTRAINT PK_whatever;
ALTER TABLE whatever WITH CHECK
ADD CONSTRAINT PK_whatever PRIMARY KEY CLUSTERED (RowId);
ALTER TABLE whatever
DROP COLUMN oldPKcolumn;
And a random thought... are you trying to reset an IDENTITY column?
If so, then use DBCC CHECKIDENT
Just a comment to improve these great answers (can't use comments yet - I'm one reputation point away from that privilege) and as future reference for myself:
A new IDENTITY (autonumber) column can be added and made the primary key in a single statement as well:
ALTER TABLE [TableName] ADD [ColumnName] int IDENTITY PRIMARY KEY;
I prefer not to bother with constraint names when it doesn't help.
You can specify seed (and increment) values between parantheses after the IDENTITY keyword.

Resources