How to create a surrogate key column in existing table? - sql

I would like to create a new column called PurchaseOrderID in an existing table using SSMS. It combines LineNumber and PONUMBER to create a surrogate key and then I would enter into table design mode and assign it a PK there.
Creating new column:
ALTER TABLE FactPurchaseOrders
ADD PurchaseOrderID VARCHAR(64);
Populating with values:
UPDATE FactPurchaseOrders
SET PurchaseOrderID = (CONVERT(VARCHAR(64), LineNumber) + CONVERT(VARCHAR(64), PONUMBER))
WHERE 1=1;
Currently with this I am unable to assign this column a PK and I believe because it is nullable.
I have also tried creating it in design mode first and the same problem occurs.

That is most certainly the case. After you have run your update, simply alter the columns you will use in your PK to NOT NULL. Since the columns will have values now it can be set as NOT NULL and then it will allow the assignment of PK. Also make sure there isn't already another PK on the table already. There can be only 1!
Update Records
Alter columns to not null
Create PK on fields

Related

Can´t add field without foreign key

I have two database one local and other in production.
In one of them I have column IdNivelDominio without FK but if I open Constraints folder and I have something like:
DF_EvaluacionDetalleCompetenciasFuncionales_IdNivelDominio
So I want to reply this field into my another database as:
ALTER TABLE Reclutamiento.EvaluacionDetalleCompetenciasFuncionales
ADD IdNivelDominio INT NOT NULL;
But I get error:
ALTER TABLE only allows columns to be added that can contain nulls, or
have a DEFAULT definition specified, or the column being added is an
identity or timestamp column, or alternatively if none of the previous
conditions are satisfied the table must be empty to allow addition of
this column. Column 'IdNivelDominio' cannot be added to non-empty
table 'EvaluacionDetalleCompetenciasFuncionales' because it does not
satisfy these conditions.
Problem is that field is not linked with a foreign key (into original table) so I can´t add constraint.
Can anyone explain me how it occurs? or there any way to do constraint without foreign key? Regards
ALTER TABLE Reclutamiento.EvaluacionDetalleCompetenciasFuncionales
ADD IdNivelDominio INT NOT NULL DEFAULT 0;
You're trying to add a new column that should be NOT NULL to table with data. You need to specify what value will be in that new column because it's NOT NULL

How to add not null unique column to existing table

Is there any way to simply add not null unique column to existing table. Something like default = 1++ ? Or simply add unique column?
I tried to add column and then put unique contrain but MS SQL says that:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name (...) The duplicate key value is ( < NULL > ).
Any way to simply add column to existing working table with unique constrain? Should MS SQL really think that null IS a value?
Add not null column with some default.
Update column to be a sequential integers (see row_number() function)
Add UNIQUE constraint or UNIQUE index over new column
You can add IDENTITY column to a table (but from question it is not clear if you need it or not).
IDENTITY is all you need:
ALTER TABLE TestTable
ADD ID INT IDENTITY(1, 1)
If you want an autonumber, you can add an identity.
If you need to populate the values yourself, you add the column allowing nulls, update the values, check to make sure they are unique and that there are no nulls, then add the unique constraint and trhe not null property. It is best to do this during a maintenance window when no one else would be changing data in that table.

primary keys are shifted

Background Information
For some reason, while inserting a huge data into multiple tables from xml, my primary keys are shifted by an offset.. (Maybe because of multiple failed attempts :P)
I have two tables.. tableA and tableB. They are in one-to-may relationship.
tableA is the parent table and has the Primary key column ...say DataIndex.
now DataIndex has come out like this..
685, 686, 687... and so on.
and corresponding values present in the child table i.e TableB are the same.
Problem
How do I shift the values up so that DataIndex start from 1, 2, 3..and so on; In both tables ?
I'm assuming that the primary key is actually an identity column that auto-increments itself upon insertion. What you will need to do is 'reseed' the identity column. You can do this by renaming the table, create a duplicate table with the original name, then inserting the data from the old table to the new one (the primary key field will be reset and will auto-increment from 1 again). When doing the insertion, make sure to include the old primary key value as an additional column for reference in the other tables.
To match up the related table, all you will need to do is do an UPDATE and join to your new table on the old primary key value:
UPDATE tableB SET
PRIMARYKEYCOLUMN = tableA.PRIMARYKEYCOLUMN
FROM tableA
WHERE
tableA.OLDPRIMARYKEYCOLUMN = tableB.PRIMARYKEYCOLUMN
I would do the following:
construct a list of Foreign Keys pointing to your PK;
ALTER all FKs, adding ON UPDATE CASCADE clause. This step might not work for some databases, you might need to DROP and CREATE constraint again;
Find the smallest current PK values, like: SELECT min(id) FROM tableA;
Refresh PK values: UPDATE tableA SET id = id - min_id + 1;
Remove ON UPDATE CASCADE clause.
Note, that depending on the tableA size and the database engine you're using, it might be faster and easier to completely rebuild the table to avoid bloat of data files.
Remove PK
Walk through records eith DB CURSOR or write a script on any language sequentally reading and changing id's
Restore PK
Setup correct identity seed for the PK
Changing seed might involve identity column drop and recreate.

SQL: Create new column with default, unique value

I have added a new column, called Ordinal, to a table called Activity. The problem is that I gave it a UNIQUE constraint, set it to allow NULL (though this I won't want in the end.. I just needed to set it to that to get a little farther with the script), and did not give it a default value. I'm now running a RedGate SQL Compare script that was generated by comparing this table to a version of the Activity table that does not have the column. But I'm getting the following error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'iwt.Activity' and the index name 'IX_Activity'. The duplicate key value is (1).
So based on my research, it's trying to create a unique key constraint on the Ordinal column, but NULL is not unique. So my next step was to give it a unique value of 1 just to let the script pass. But 1 isn't going to be unique either. So, finally, my question:
Preferably in SQL Server Management Studio, how do I set a column as having a unique default value? Isn't that what I would need to create this constraint?
Thanks.
try this:
NULL will be the first constraint when you create the column.
UNIQUE will be as add constraint, you should add the second constraint.
they can run on this order with no problem (tested):
--first constraint
alter table Table_Name
add Column_Name int null
--second constraint
alter table Table_Name
add constraint Constraint_Name unique (Column_Name)
In my example :
PaymentGatewayHash is column
Cart is a table
--first query
alter table Cart
add PaymentGatewayHash NVARCHAR(20) null
--second query
CREATE UNIQUE INDEX PaymentGatewayHashUnique
ON Cart (PaymentGatewayHash)
WHERE PaymentGatewayHash IS NOT NULL
I just tested that :D

Is there a smart way to append a number to an PK identity column in a Relational database w/o total catastrophe?

It's far from the ideal situation, but I need to fix a database by appending the number "1" to the PK Identiy column which has FK relations to four other tables. I'm basically making a four digit number a five digit number. I need to maintain the relations. I could store the number in a var, do a Set query and append the 1, and do that for each table...
Is there a better way of doing this?
You say you are using an identity data type for your primary key so before you update the numbers you will have to SET IDENTITY_INSERT ON (documentation here) and then turn it off again after the update.
As long as you have cascading updates set for your relations the other tables should be updated automatically.
EDIT: As it's not possible to change an identity value I guess you have to export the data, set the new identity values (+10000) and then import your data again.
Anyone have a better suggestion...
Consider adding another field to the PK instead of extending the length of the PK field. Your new field will have to cascade to the related tables, like a field length increase would, but you get to retain your original PK values.
My suggestion is:
Stop writing to the tables.
Copy the tables to new tables with the new PK.
Rename the old tables to backup names.
Rename the new tables to the original table name.
Count the rows in all the tables and double check your work.
Continue using the tables.
Changing a PK after the fact is not fun.
If the column in question has an identity property on it, it gets complicated. This is more-or-less how I'd do it:
Back up your database.
Put it in single user mode. You don't need anybody mucking around whilst you do the surgery.
Execute the ALTER TABLE statements necessary to
disable the primary key constraint on the table in question
disable all triggers on the table in question
disable all foreign key constraints referencing the table in question.
Clone your table, giving it a new name and a column-for-column identical definitions. Don't bother with any triggers, indices, foreign keys or other constraints. Omit the identity property from the table's definition.
Create a new 'map' table that will map your old id values to the new value:
create table dbo.pk_map
(
old_id int not null primary key clustered ,
new_id int not null unique nonclustered ,
)
Populate the map table:
insert dbo.pk_map
select old_id = old.id ,
new_id = f( old.id ) // f(x) is the desired transform
from dbo.tableInQuestion old
Populate your new table, giving the primary key column the new value:
insert dbo.tableInQuestion_NEW
select id = map.id ,
...
from dbo.tableInQuestion old
join dbo.pk_map map on map.old_id = old.id
Truncate the original table: TRUNCATE dbo.tableInQuestion. This should work—safely—since you've disabled all the triggers and foreign key constraints.
Execute SET IDENTITY_INSERT dbo.tableInQuestion ON.
Reload the original table:
insert dbo.tableInQuestion
select *
from dbo.tableInQuestion_NEW
Execute SET IDENTITY_INSERT dbo.tableInQuestion OFF
Execute drop table dbo.tableInQuestion_NEW. We're all done with it.
Execute DBCC CHECKIDENT( dbo.tableInQuestion , reseed ) to get the identity counter back in sync with the data in the table.
Now, use the map table to propagate the changed primary key column down the line. Depending on your E-R model, this can get complicated as foreign keys referencing the updated column may themselves be part of a composite primary key.
When you're all done, start re-enabling the constraints and triggers you disabled. Make sure you do this using the WITH CHECK option. Fix any problems thus uncovered.
Finally, drop the map table, and clear the single user flag and bring your system(s) back online.
Piece of cake! (or something.)
Consider this approach:
Reset the identity seed to the 10000 + the current seed.
Set identity insert on
Insert into the table from the values in the table and add 10000 to the identity column on the way.
EX:
Set identity insert on
Insert Table(identity, column1, eolumn2)
select identity + 10000, column1, column2
From Table
Where identity < origional max identity value
After the insert you know the identity is exactly 10000 more than the origional.
Update the foreign keys by addding 10000.