How do I modify a primary key column so that it's auto-generated? [duplicate] - sql-server

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to set auto increment after creating a table without any data loss?
How do I modify the primary key column (integer type) of a SQL Server 2012 table so that it's auto-generated?

CREATE TABLE dbo.Test(PkCol int CONSTRAINT PK_Test_PkCol PRIMARY KEY, OtherCol varchar(1));
ALTER TABLE dbo.Test
DROP CONSTRAINT PK_Test_PkCol
GO
ALTER TABLE dbo.Test DROP COLUMN PkCol
ALTER TABLE dbo.Test
ADD PkCol int IDENTITY(1,1) CONSTRAINT PK_Test_PkCol PRIMARY KEY
GO
IDENTITY

You can drop the existing column and add a new column with the column type specified as IDENTITY.
But beware!
I liked and copied the below comment from here:
If you just drop the existing column and add a new column with the same name but define it as identity, you’ll might modify the value of the primary key for some of the records in the table. There is no guarantee that the new column will get the same values as the old columns.
Since there is no way to modify the column itself to be an identity column, you’ll have to create a new table with an identity column, insert the data from the old table into the new table (with set identity_insert on you’ll get the same values in the new column as you had in the old column), rename or drop the original table (It is better to rename it first, so you’ll be able to roll back the modification if something goes wrong), rename the new table to the original table’s name, recreate the foreign keys that referenced the original table and run dbcc checkident to initialize the identity’s seed to the next number.

Since you said SQL 2012, you have another option: sequences. Check out Books Online on how to use "next value for" as a default for a column.

Related

Drop column with PK constraint in empty table in a script

Scenario
A table in SQL Server has two or more columns, but the original column with the primary key constraint is no longer needed. So now you want to write a script to drop the original column w/ a PK constraint and put the PK constraint on a different column.
In this example, the table is empty.
Problem
You can't drop the first column without first dropping the PK constraint.
And you can't drop the PK constraint in SQL Server without the exact name of it. (more info here)
....But you don't know the automatically generated name of the PK constraint.
NOTE: If the table is not empty, see this solution:
SQL Server 2008 Script to Drop PK Constraint that has a System Generated Name
(In most cases, this is the best solution.)
Question
The above solution will work, but what is another way to script dropping a column with a PK constraint when you don't know the constraint's name in an empty table?
Another strategy -- besides figuring out the system generated name of the PK constraint so you can drop it as described here -- is to drop the empty table and recreate it without the original column with the primary key constraint, instead putting it on the new column.
To drop the column with an unknown PK constraint name:
Generate a script to drop the table and re-create it from scratch
Remove the OriginalColumn column from the CREATE TABLE query
Put the PK constraint on the NewColumn column in the script
Run the script to drop and re-create it without the original column -- effectively dropping OriginalColumn and "moving" the PK constraint from OriginalColumn to NewColumn
???
Profit!

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

How do you add a unique primary key field automatically in SQL Server?

I am using SQL Server 2012 and need to add a column with a unique primary key. I am about to load several hundred thousand records BULK and just discovered repetition in the field I was going to use. Have seen SEQUENCE and GUID. Need some guidance on the best choice and how to go about setting this up so that the key field is populated during the bulk load.
When you create your table in which you want to insert information create an IDENTITY column. That will serve as an auto-populating column with a unique number for each record.
Here is a link that might help you.
If you have already created your table just change this query to what suits to your table name and run it in order to add the new column you requested.
ALTER TABLE mytable
ADD COLUMN unique_id IDENTITY (1,1)
Just a slight update on what’s already posted that includes details for adding primary key constraint
alter table database.schema.table_t
add ID_column int identity(1,1)
primary key (ID_column)
If you already set the primary key on this table just go and remove it before you execute this statement.

Auto increment primary key in SQL Server Management Studio 2012

How do I auto increment the primary key in a SQL Server database table? I've had a look through the forum but can't see how to do this.
I've looked at the properties but can't see an option. I saw an answer where you go to the Identity specification property and set it to yes and set the Identity increment to 1, but that section is grayed out and I can't change the no to yes.
There must be a simple way to do this but I can't find it.
Make sure that the Key column's datatype is int and then setting identity manually, as image shows
Or just run this code
-- ID is the name of the [to be] identity column
ALTER TABLE [yourTable] DROP COLUMN ID
ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)
the code will run, if ID is not the only column in the table
image reference fifo's
When you're creating the table, you can create an IDENTITY column as follows:
CREATE TABLE (
ID_column INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
...
);
The IDENTITY property will auto-increment the column up from number 1. (Note that the data type of the column has to be an integer.) If you want to add this to an existing column, use an ALTER TABLE command.
Edit:
Tested a bit, and I can't find a way to change the Identity properties via the Column Properties window for various tables. I guess if you want to make a column an identity column, you HAVE to use an ALTER TABLE command.
You have to expand the Identity section to expose increment and seed.
Edit: I assumed that you'd have an integer datatype, not char(10). Which is reasonable I'd say and valid when I posted this answer
Expand your database, expand your table right click on your table and select design from dropdown.
Now go Column properties below of it scroll down and find Identity Specification, expand it and you will find Is Identity make it Yes. Now choose Identity Increment right below of it give the value you want to increment in it.
CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid" column (a unique value will be added automatically):
Perhaps I'm missing something but why doesn't this work with the SEQUENCE object? Is this not what you're looking for?
Example:
CREATE SCHEMA blah.
GO
CREATE SEQUENCE blah.blahsequence
START WITH 1
INCREMENT BY 1
NO CYCLE;
CREATE TABLE blah.de_blah_blah
(numbers bigint PRIMARY KEY NOT NULL
......etc
When referencing the squence in say an INSERT command just use:
NEXT VALUE FOR blah.blahsequence
More information and options for SEQUENCE
When you're using Data Type: int you can select the row which you want to get autoincremented and go to the column properties tag. There you can set the identity to 'yes'. The starting value for autoincrement can also be edited there. Hope I could help ;)
I had this issue where I had already created the table and could not change it without dropping the table so what I did was:
(Not sure when they implemented this but had it in SQL 2016)
Right click on the table in the Object Explorer:
Script Table as > DROP And CREATE To > New Query Editor Window
Then do the edit to the script said by Josien; scroll to the bottom where the CREATE TABLE is, find your Primary Key and append IDENTITY(1,1) to the end before the comma. Run script.
The DROP and CREATE script was also helpful for me because of this issue. (Which the generated script handles.)
You can use the keyword IDENTITY as the data type to the column along with PRIMARY KEY constraint when creating the table.
ex:
StudentNumber IDENTITY(1,1) PRIMARY KEY
In here the first '1' means the starting value and the second '1' is the incrementing value.
If the table is already populated it is not possible to change a column to IDENTITY column or convert it to non IDENTITY column. You would need to export all the data out then you can change column type to IDENTITY or vice versa and then import data back.
I know it is painful process but I believe there is no alternative except for using sequence as mentioned in this post.
Be carefull like if you want the ID elements to be contigius or not. As SQLSERVER ID can jump by 1000 .
Examle: before restart ID=11
after restart , you insert new row in the table, then the id will be 1012.
You could do the following: New Table Creation:
-- create new table with Column ID which is Primary Key and Auto Increment --
CREATE TABLE titles(
id INT NOT NULL IDENTITY(1,1) PRIMARY KEY, --Primary Key with Auto-Increment --
keyword VARCHAR(260),
status VARCHAR(10),
);
If you Table Already exists and need to make the changes to ID column to be auto-increment and Primary key, then see below:
ALTER TABLE table DROP COLUMN id; // drop the existing ID in the table
ALTER TABLE table ADD id int IDENTITY(1, 1) NOT NULL; // add new column ID with auto-increment
ALTER TABLE table ADD CONSTRAINT PK_ident_test PRIMARY KEY CLUSTERED (id); // make it primary key

SQL Server Compact alter column size with constraint?

I am trying to modify the size of a column in a table, however that column is a primary key column and is used in other table ( which would need to have its size modified too)
I have a table called table1 with a column named column1 as primary key
I also have table2,table3 and table4 that has table2column1, table3column1 and table4column1 respectively.
table2column1,table3column1 and table4column1 are foreign keys ( reference column1 from table1) and they are also used as a composite primary key in their respective table.
I tried doing this to alter the size of the column
ALTER TABLE UtilisateurNotes ALTER COLUMN IDNotes nvarchar(250)
It did not work.
This is the error message : Cannot alter a column that is part of a key or an index.
Anyone has an idea what I should do? thank you Gibit
You have to drop the foreign keys and primary key index in order to modify the column and then rebuild them after.
If you're in SQL Server Management Studio and you use the Object Explorer then you can right click on the specific Primary Key or Foreign Key specified in the error message and use Script as > CREATE AND DROP to help you generate the necessary scripts for the update.

Resources