SQL Server : set primary key without dropping table and content [duplicate] - sql

This question already has answers here:
SQL Server add auto increment primary key to existing table
(16 answers)
Add primary key column in SQL table
(3 answers)
Closed 9 years ago.
Is it possible to set the primary key and auto increment on a SQL Server table without dropping and recreating the table, and losing all it's data?

Yes of course! You just add a new column, and it an INT IDENTITY and add a primary key constraint to it:
ALTER TABLE dbo.YourTable
ADD ID INT IDENTITY(1,1) NOT NULL
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable PRIMARY KEY (ID)

If there is an existing primary key, you must first drop it:
IF EXISTS (SELECT * FROM sys.key_constraints
WHERE type = 'PK' AND parent_object_id = OBJECT_ID('MyTable')
AND Name = 'PK_MyTable')
ALTER TABLE MyTable DROP CONSTRAINT PK_MyTable
If you are adding a column to be used as a primary key, then you can simply add it:
ALTER TABLE MyTable ADD MyKey INT IDENTITY
Then, you can set this column as your table's primary key:
ALTER TABLE MyTable ADD CONSTRAINT PK_MyTable PRIMARY KEY(MyKey)

Related

SQL Create Table Columns [duplicate]

This question already has answers here:
Creating a computed column in SQL Server 2008
(2 answers)
Closed 2 years ago.
I want a column in sql to be the sum of 2 columns in the same table.
For example:
columns : score, assists, rebound
While creating this table ı want score = assist + rebound value.
CREATE TABLE macDetay (
macID INT , oyuncuID INT ,
CONSTRAINT PKDETAY PRIMARY KEY (macID, oyuncuID),
CONSTRAINT FK1 FOREIGN KEY(macID) REFERENCES Mac(macID),
CONSTRAINT FK2 FOREIGN KEY(oyuncuID) REFERENCES Oyuncu(oyuncuID),
macSkor INT, asistSayisi INT,reboundSayisi INT,
CONSTRAINT skor CHECK (macSkor = asistSayisi+ReboundSayisi))
I'm forcing to enter the sum in my way but I want it to be automatic
You can add computed column in your statement. It's simple.
computedColumnName as (col1 + col2)
CREATE TABLE macDetay (
macID INT
,oyuncuID INT
,CONSTRAINT PKDETAY PRIMARY KEY (
macID
,oyuncuID
)
,CONSTRAINT FK1 FOREIGN KEY (macID) REFERENCES Mac(macID)
,CONSTRAINT FK2 FOREIGN KEY (oyuncuID) REFERENCES Oyuncu(oyuncuID)
,macSkor AS (asistSayisi + ReboundSayisi)
,asistSayisi INT
,reboundSayisi INT
)

Switch primary key constraint to a new column

I want to switch the primary key away from my existing identity column
to a different column.
This is my table:
CREATE TABLE dbo.ParkingLot
(
ID int IDENTITY(1,1) PRIMARY KEY,
Address ???,
Status ???,
newID ???
);
I want to remove the primary key on the ID column and instead have newID be the primary key (this is a new column but it is already populated with values).
Drop primary Key constraint and Re-Add a new one
You have to drop the primary key constraint and add a new one
Drop primary key Constraint
-- Return the name of primary key.
SELECT name
FROM sys.key_constraints
WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) =
N'Tablename';
GO
-- Delete the primary key constraint.
ALTER TABLE Production.Tablename
DROP CONSTRAINT PK_Tablename;
GO
Add new primary key Constraint
ALTER TABLE Tablename ADD CONSTRAINT pk_NewPrimary PRIMARY KEY (Newid)
References
Delete Primary Keys
Change primary key column in SQL Server

ALTER COLUMN Command doesn't work SQL Server

i want to add to a primary key in one table a references to the primary key of another table.
my code:
CREATE TABLE[payment]
(ID int Primary key)
CREATE TABLE [tab]
(ID int Primary key references tab2(ID))
Alter Table payment
alter column ID
ADD constraint fk_payment
references tab(ID)
i get the error that the syntax near constraint is wrong, but i don't know what to change
because of the not changeable order of the table Alter table is the only option. to reference from one table to the other doesn't work cause I've references from that table to another one already.
i need two one-to-one-relations from one table to another
If you want to add a FK constraint, just use this code:
ALTER TABLE dbo.payment
ADD CONSTRAINT fk_payment
FOREIGN KEY(ID) REFERENCES dbo.tab(ID)
You don't need to alter the column or table - just add the constraint

azure db drop pk and add a new one

I have MS SQL database on Azure , and I want to drop my Primary key constraint and add another column as a primary key , every time I try to run the script to drop the primary key I get the error:
" Tables without a clustered index are not supported in this version of SQL Server. Please create a clustered index and try again."
by running this script:
IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.Paypaltransaction') AND Name = 'PK_PaypalTransaction')
ALTER TABLE dbo.PaypalTransaction
DROP CONSTRAINT PK_PaypalTransaction
GO
Then I go and try to create another primary key :
-- add new primary key constraint on new column
ALTER TABLE dbo.PaypalTransaction
ADD CONSTRAINT PK_PaypalTransactionId
PRIMARY KEY CLUSTERED (PaypalTransactionId)
GO
and I get this error:
"Table 'PaypalTransaction' already has a primary key defined on it."
I understand the error's , but I can't delete the primary key because it appearently has to have one , and I can't add a new one because I already have one . Am I just stuck forever and ever and ever with the wrong column as my primary key :'(
I see This Question here that is the same and they ended up dropping the table and creating a new one - no way that is the only way to do this , that is just silly.
Copy over from the DBA.Se answer:
Q5) Can the primary key of a table be modified when is enforced via the clustered index if the table is populated?
A: No. Any operation that converts a populated clustered index into a heap will be blocked in SQL Azure, even if the table is empty:
create table Friend (
UserId int not null,
Id int not null identity(1,1),
constraint pk_Friend primary key clustered (UserId, Id));
go
insert into Friend (UserId) values (1);
delete from Friend;
go
alter table Friend drop constraint pk_Friend;
As a side note: the constraint can be modified if the table is truncated.
The workaround to change the PK constraint of a populated table is to do the good old sp_rename trick:
create table Friend (
UserId int not null,
Id int not null identity(1,1),
constraint pk_Friend primary key clustered (UserId, Id));
go
insert into Friend (UserId) values (1);
go
create table FriendNew (
UserId int not null,
Id int not null identity(1,1),
constraint pk_Friend_New primary key clustered (Id, UserId));
go
set identity_insert FriendNew on;
insert into FriendNew (UserId, Id)
select UserId, Id
from Friend;
set identity_insert FriendNew off;
go
begin transaction
exec sp_rename 'Friend', 'FriendOld';
exec sp_rename 'FriendNew', 'Friend';
commit;
go
sp_help 'Friend';
The sp_rename approach has some issues, most importantly being that permissions on the table do not carry over during the rename, as well as foreign key constraints.
I have just tested and it seems that on SQL AZURE V12 it is possible!

Alter a table column with auto increment by 1 in derby

I have created a table in derby Netbeans and now i realize that i need to make a column as auto incremented by 1 which is a primary key. How can i do so? I tried the following code but was in vain.
ALTER TABLE ISSUERECIPT ALTER IRCODE SET INCREMENT BY 1;
Do i need to create the table once again or can it be possible some other way?
I have found an alternate solution, i dropped the column from the database (thanks vels4j) added the column once again from the netbeans derby UI as shown below:
To alter the column to be auto-generated, the code is
ALTER TABLE ISSUERECIPT ALTER IRCODE SET INCREMENT BY 1;
BUT the column must already be defined with the IDENTITY attribute (as written in this documentation).
In most cases (assuming that you too), the primary key column is not set as IDENTITY. Therefore, you may intend to alter the column to IDENTITY, but that is impossible.
The only way is to drop the table and create it again, as written here.
ALTER TABLE ISSUERECIPT ADD IRCODE INTEGER NOT NULL primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
I guess could do the things for you
Check this
ALTER TABLE ISSUERECIPT
ALTER IRCODE INTEGER NOT NULL
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1);
If your table is empty, Try this
ALTER TABLE DROP PRIMARY KEY your_primaryKeyContrainName ;
ALTER TABLE ISSUERECIPT DROP COLUMN IRCODE ;
ALTER TABLE ISSUERECIPT ADD COLUMN
IRCODE PRIMARY KEY INTEGER NOT NULL
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1);
See Also : Derby ALTER TABLE Syntax
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
The ALTER TABLE statement cannot add an IDENTITY column to a table
If your table is empty or is not in production. drop table and create again, example:
DROP TABLE CUSTOMER;
CREATE TABLE CUSTOMER
(CUSTOMER_ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY
1),
FIRSTNAME VARCHAR(100) NOT NULL,VARCHAR(100),
PREFERRED_ID INTEGER,
CONSTRAINT primary_key PRIMARY KEY (CUSTOMER_ID)
);
Try this :
alter table ISSUERECIPT modify column IRCODE int(4) auto_increment
Recreate the table again see example below:
CREATE TABLE students
(
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
name VARCHAR(24) NOT NULL,
address VARCHAR(1024),
CONSTRAINT primary_key PRIMARY KEY (id)
) ;