I need to delete existing PK from table and create new in new column. Because column for new PK was added later (after table creation) - we have nulls for old rows. Should I use UPDATE statement or there is some option in "ADD CONSTRAINT" clause which automatically determine NULLs and generate GUIDs for them?
Thanks for help.
This is what you have to do.
UPDATE TABLE1
SET GUID = NEWID()
WHERE GUID IS NULL
Now to add a new contstraint, you will have tod elete the old one. This is how you can do it:
ALTER TABLE TABLE1
DROP CONSTRAINT PrimaryKeyName
ALTER TABLE TABLE1
ADD CONSTRAINT PrimaryKeyName PRIMARY KEY (GUID)
Related
I have two tables which we will call Event and EventResponse
Event has PK eventGuid varchar(36) and several other columns
EventResponse has FK eventGuid varchar(36) and other columns
I can easily add an INT identity column to Event with:
ALTER TABLE dbo.[Event]
ADD eventId INT IDENTITY;
And adding a column to EventResponse table is Ok.
How do I update all the eventIds in the response table?
Is this possible with a neat query or do I have to loop through?
Final state should be:
Event has PK eventId, eventGuid varchar(36), other columns
EventResponse has FK eventId, eventGuid varchar(36), other columns
No looping required. Words to live by :)
This should be just about all you need. Use your existing foreign key to update the values for your new key, then drop the old relationship and add the new one.
UPDATE er
SET er.eventID = e.eventID
FROM
dbo.EventResponse AS er
JOIN
dbo.Event as e
ON er.eventGuid = e.eventGuid;
GO
ALTER TABLE dbo.EventResponse
DROP CONSTRAINT <FK_Name>
GO
ALTER TABLE dbo.EventResponse
ADD CONSTRAINT <FK_Name> FOREIGN KEY (eventId)
REFERENCES dbo.Event(eventId)
[ON DELETE CASCADE
ON UPDATE CASCADE]
GO
Then, probably, if you want to save some space in your database:
ALTER TABLE dbo.Event
DROP COLUMN eventGuid;
GO
ALTER TABLE dbo.EventResponse
DROP COLUMN eventGuid;
GO
try this:
update a set a.eventId=b.eventId
from EventResponse a
inner join Event b on a.eventGuid = b.eventGuid
I'm using psql and I want to change one of the columns of my table.
At the moment this column is a foreign key of Table 2 but I would like to make it point to Table 3.
Is this possible or should I delete the column and add a new one?
There's no need to add & remove the column. You can remove/disable the constraint to one table and add it for the other table.
The command for doing the former is:
alter table Table1 drop constraint if exists name_of_constraint_on_Table_1_column
The command for doing the latter is:
alter table Table1
add constraint name_of_constraint_on_Table_1_column
foreign key (column) references Table3 (other_column) match full
You need to find the name of the foreign key constraint if you haven't named it explicitly. You can do so via the \d command:
\d Table1
You should read about alter table cause there's a lot of things you can do to change the table.
I have a table with 100 rows, but my primary key column is not with identity property.(but values of this column seems like identity column and sequential: 1-100)
Now i tried to add new identity column with below code
alter table tableA add new_Iden_col bigint identity(1,1)
but i find that the new column identity values are not in sorted order as per my primary key column.
my output of old Primary key col and new inserted identity column
So can someone explain me why the newly added column is not same as my primary key column even though my old column values are populated naturally in same way and not dynamically sorted for output.
Thanks in advance. :)
The IDENTITY function can be used to create a new IDENTITY column and assign incremental values in the sequence specified by the ORDER BY clause of SELECT...INTO. Below is an example creates a new IDENTITY column for use as a new primary key from the old primary key column order.
SELECT
IDENTITY(bigint, 1,1) AS new_Ident_col
, OtherData
INTO FROM dbo.TableA_New
FROM dbo.TableA
ORDER BY old_PK_col;
DROP TABLE dbo.TableA;
EXEC sp_rename 'dbo.TableA_New', 'TableA';
ALTER TABLE dbo.TableA ADD CONSTRAINT PK_TableA PRIMARY KEY(new_Ident_col);
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 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.