sql server helper stored procedure or utility for alter table alter column IDENTITY(1,1) - sql

I wanted to modify a column in a sql server 2005 table to IDENTITY(1,1)
Incidentally this table is empty and the column to be changed is a primary key.
This column is also a foreign key for two other tables.
After googling I found that you cannot use Alter table syntax to modify a column and make it an indentity column.
Link #1 : How do I add the identity property to an existing column in SQL Server
Link #2 : Adding an identity to an existing column -SQL Server
I ended up checking the dependent tables (2 of them) removing the foreign keys (generated the script from SSMS) then dropping the main table then re-creating with identity. (could try the rename option here as well)
Then re-created the foreign keys for the earlier dependent two tables.
But all this was manual work, any scripts or SPs out there to make this easier.
Ideally all these steps would be done by such a script/tool/utility:
Check dependent tables keys
Generate Create and drop foreign key scripts for this
Generate create script for the main table
drop the main table (or rename the table if the table has data)
re-create the table with identity column enabled
re-create foreign keys

You can use SSMS to generate a script (Edit a table, save script), but otherwise it's a manual process as you identified.
The SSMS scripts will pick up dependencies etc. For this kind of work, I tend to use SSMS to generate a basic script, pimp it a bit, run it carefully, then use a comparison tool (such as Red Gate compare) to generate a safer version.
Edit: The SSMS error is not an error, it's a safety check that can be switched off

(This is merely a follow-up to gbn's post with more details -- it isn't all that easy to figure this stuff out.)(
It isn't impossible to write a utility to do this, just very complex and very hard. Fortunately, Microsoft has already done it -- its called SSMS (or SMO?). To generate such a script:
In the Object Explorer, drill down to the database and table that you want to modify
Right click and select Design
Make the desired changes to the one table in the design screen. It's reasonably intuitive.
To add/remove the identity property, select the column in the upper pane, and in the lower pane/"Column Properties" tab, expand and configure the settings under "Identity Specification".
To generate a script to implement all your changes, incorporating all the dependent key changes, click on the "Generate Change Script" toolbar button. This is also an option under the "Table Designer" menu.
I also do this to generate scripts (that I later modify--SSMS doesn't always produce the most efficient code.) Once done, you can exit out without saving your changes -- leaving you a DB you can test your new script on.

drop the pk and build the same datatype column
copy the data of the column which you want to set identity to the new column.
drop the old column
reset primary key
ALTER TABLE UserRole
DROP CONSTRAINT PK_XX
ALTER TABLE XX
ADD newX int not null identity(1,1) primary key
update XX set newX = oldX
alter table XX
DROP COLUMN oldX
this is the simplest way to set identity column.
if you don't want to use the long generated script.

Related

How to transfer data using SSIS

I am new to SSIS packages and just require assistance on how to transfer data from one data source onto my own database.
Below is my data flow:
Now I have a ODBC Source (Http_Requests Source) where I take data from a PostgreSQL database table (see screenshot below for table columns and data):
Below is the OLE DB destination where it has the table I want to transfer the data to (this table is currently blank):
Now I tried to start debugging to extract the data but I get a few errors (displayed below):
I am a complete novice so I would like some guidance on what I need to include in order to get this SSIS package to transfer data across. Would I need to include a merge statement and how do I apply it. I heard you can write a merge as a proc and call on the proc as a sql command. Does that mean I will need to write a proc in SSMS and then call on it within the OLE DB Destination?
If somebody can provide an example and screenshot then that would be very helpful as I am really new to SSIS.
Thank you,
Check constraint on destination table or disable them before running it.
Below are query you can use.
-- Disable all table constraints
ALTER TABLE YourTableName NOCHECK CONSTRAINT ALL
-- Enable all table constraints
ALTER TABLE YourTableName CHECK CONSTRAINT ALL
Tick keep identity
box or drop primary key on the table. After you apply the changes do not forget to refresh metadata by opening the mappings in sis.
the error means that PerformanceId is an IDENTITY column on your destination table. IDENTITY columns are read only unless you tell it otherwise. So if we were in tSQL to be able to insert IDENTITY we would turn on IDENTITY_INSERT. Because you are in SSIS you can accomplish the same thing by checking the "keep identity" box.
HOWEVER when ever you get an error like this it is usually a sign that you should NOT be mapping ID to Performance ID. The question you have to ask is the Identity from your source supposed to be the identity of the destination table? Usually not, most of the time it would be another column as a surrogate key. Then you have to understand if it is even possible. because if there is a unique constraint or primary key then the identity cannot repeat which means you have to know that your source's id column will not cause a duplicate primary key violation.
More than likely the actual fix if for you to uncheck ID from the source and ignore the value.
The column PerformanceID (in the target) is almost certainly an identity column and that is why it is not working. You may not want to transfer it (and have SQL Server generate values for PerformanceID or you can check 'Keep Identity.'

SQL Server: Existing column and value incrementing

I'm trying to create and increment by one some values to put into an already existing (but empty) column. I'm currently using the identity function, but I wouldn't mind using a custom made function. Right now, SSMS is saying there's incorrect syntax near IDENTITY. Could anybody help me fix this syntax?
ALTER Table anthemID IDENTITY(1,1)
First, you can't make a column identity after the fact: it has to be set that way at creation time.
Second, I'm not quite sure what you mean by "increment the value of an already existing column by one." You can only increment the value of rows within a column--perform a DML (Data Modification Language) query. The script you suggested above is a DDL (Data Definition Language) query that actually modifies the structure of the table, affecting the entire column--all rows.
If you just want to increment all the rows by 1, you'd do this:
UPDATE dbo.YourTable SET anthemID = anthemID + 1;
On the other hand, if you want the anthemID column to acquire the identity property so that new inserts to the table receive unique, autoincrementing values, you can do that with some juggling:
Back up your database and confirm it is a good backup.
Script out your table including all constraints.
Drop all constraints on your table or other tables that involve anthemID.
ALTER TABLE dbo.YourTable DROP CONSTRAINT PK_YourTable -- if part of PK
ALTER TABLE dbo.AnotherTable DROP CONSTRAINT FK_AnotherTable_anthemID -- FKs
Rename your table
EXEC sp_rename 'dbo.YourTable', 'YourTableTemp';
Modify the script you generated above to make anthemID identity (add in identity(1,1) after int);
Run the modified script to create a new table with the same name as the original.
Insert the data from the old table to the new one:
SET IDENTITY_INSERT dbo.YourTable ON;
INSERT dbo.YourTable (anthemID, AnotherColumn, RestOfColumns)
SELECT anthemID, AnotherColumn, RestOfColumns
FROM dbo.YourTableTemp;
SET IDENTITY_INSERT dbo.YourTable OFF;
Re-add all constraints that were dropped.
Drop the original, renamed table after confirming you don't need the data any more.
You may be able to do this from SSMS's GUI table designer, and it will take care of moving the data over for you. However, this has bitten some people in the past and if you don't have a good database backup, well, don't do it because you might encounter some regret in the process.
UPDATE
Now that I know the column is blank, it's even easier.
ALTER TABLE dbo.YourTable DROP COLUMN anthemID;
ALTER TABLE dbo.YourTable ADD anthemID int identity(1,1) NOT NULL;
This does have the drawback of moving the column to the end of the table. If that's a problem, you can follow much the same procedure as I outlined above (to fix things yourself, or alternately use the designer in SQL Server Management Studio).
I recommend in the strongest terms possible that you use an identity column and do not try to create your own means of making new rows get an incremented value.
For emphasis, I'll quote #marc_s's comment above:
The SELECT MAX(ID)+1 approach is highly unsafe in a concurrent environment - in a system under some load, you will get duplicates. Don't do this yourself - don't try to reinvent the wheel - use the proper mechanisms (here: IDENTITY) that your database gives you and let the database handle all the nitty-gritty details!
I wholeheartedly agree with him.

How do I change my table's identity column datatype without losing data

The database that I am tasked with fixing has a table with an identity column/PK that has a datatype of BigInt. This causes problem with the Access front end in that a datasheet to this linked table will not allow edits to the records. (This is a known issue with ODBC drivers and Access)
The table's Id column should never have been created as a bigint in the first place but that is a moot point now. I need to convert or recreate this column with a datatype of int, without losing the existing data.
There are ~2 million records in this table.
There are an unknown number of apps and Access apps that access this table so I am trying to do this as smoothly/stealthily as possible since the likelihood of finding all of those apps and modifying them before I make the change is slim.
Any thoughts or ideas?
I'm assuming the IDENTITY column is your PRIMARY KEY, and it's probably clustered :) MY advice below is based on those assumptions.
If you've only got a few indexes on the table, and the PRIMARY KEY is only referenced by a few FOREIGN keys, you should be able to change the datatype by:
Dropping any nonclustered indexes which contain the IDENTITY value.
Dropping the FOREIGN KEY constraints which point to the PRIMARY KEY.
Drop the PRIMARY KEY
ALTER TABLE tablename ALTER COLUMN columnname INT;
REcreate the PRIMARY KEY
Re-enable the FOREIGN KEY constraints with CHECK.
Recreate your nonclustered indexes.
As RBarryYoung pointed out, a lot of this can be scripted out by the SSMS GUI (if it's configured to allow saving changes), but the difference is that the GUI will create a temporary table, move your data, rename the new table to the old name, and drop the original.
Here's how to do it from Management Studio(SSMS):
First, make a backup copy of your database. If you make a mistake, or something unexpected happens, the easiest way to fix it is to restore from backup.
In the SSMS Explorer Pane, navigate to the table, then right-click on it and click "Design".
Select the Identity column's row and change it's datatype to "INT".
Save your changes, ignore the warning.
If you need a script instead, then replace step (4) above with:
Click the Script Changes button. Ignore the warning and then copy the script into you paste buffer. Make a new query window and paste the script into it. Then close the design window, cancelling any changes.
As Stuart Ainsworth points out, in later versions of SQL Server, it may prevent you from doing this, with a warning about "Dropping a Table". To fix this in SSMS, click the Tools..Options menu entry, then go to the "Tables and Designers" pane under "Designers" and uncheck the "Prevent saving changes that require table recreation" option.

easy button for adding column

I right click on my table in ssms 2008 and select Script Table as / Drop and Create Table to new window and I try to run the script but get an error:
Could not drop table because it is referenced by a foreign key constraint
What was the point of the Drop and Create generate script then?
Thanks,
rod.
The point of the Drop and Create generate script is exactly what you'd think - it gives you an easy way to script out dropping and re-creating a table. However you can't drop a table if other tables reference it via foreign key constraints, which is why you're getting the error message.
If you're just trying to add a column, you can right-click the table in Enterprise Manager and click Modify and just add the column in design view. There's no need to drop the table just to add a column. (And it's especially an awful approach if the table has data in it.)
The easiest way to add a column to an existing table? Write the ALTER TABLE statement yourself instead of relying on SQL Server Management Studio to do it for you:
ALTER TABLE YourTableName
ADD ColumnName int

Why isn't SSMS smart when it comes to adding columns?

Whenever I want to add a column to a table it usually goes something like this:
Fire up SQL Server Management Studio (SSMS)
Select "Design" on the table I want to add the column to
Add the new column to the table
Save
Get an error that SSMS can't save because it would need to drop the table (and it can't because the the table has foreign keys on it).
Get frustrated that I forgot that this is something that SSMS can't do
Construct an alter table command by hand to add the column
Move on with life.
This time I am adding a step between numbers 6 and 7. I thought I would ask why SSMS can't make a simple alter table statement to add my new column in.
(In case it matters I am running SSMS 2008 against SQL Server 2008.)
Alternatively, you can go to Tools-->Options-->Designers-->Table and Database Designers and uncheck "Prevent saving changes that require table re-creation"
Problem solved.
Here's an explanation from MSDN: http://support.microsoft.com/default.aspx/kb/956176.
When you change a table so that you
alter the metadata structure of the
table, and then you save the table,
the table must be re-created based on
these changes.