Alter table set Identity column - sybase

I have a sybase table ("Test") having the following columns:
MyIdentity numberic(9,0)
Name
User
The table is filled with lots of records. I want to alter MyIdentity column to be an identity.
There are currently no duplicate values for MyIdentity in the table. How can i alter the table and set MyIdentity as identity?

Apparently you can't, something like
Create a new Table called test2 with the identity set up
Then
Set Identity_Insert Test2 On
Insert Test2 Select * From Test
Set Identity_Insert Test2 Off
Drop Test and Rename Test 2...

At least on my version (Adaptive Server Enterprise/15.0.3) the following seems to do the trick (syntactic sugar omitted):
Add a new identity column:
alter table Test add newMyIdentity numeric(9,0) identity not null
Prepare for updates:
set identity_insert Test on
set identity_update Test on
Copy the existing ID (to be able to preserve foreign keys etc):
update Test set newMyIdentity=MyIdentity
Drop the old definition, rename the newly created column:
alter table Test drop MyIdentity
sp_rename "Test.newMyIdentity", MyIdentity
Clean up:
set identity_insert Test off
set identity_update Test off
sp_recompile Test

Just use:
create index MyIdentity on Test
See http://manuals.sybase.com/onlinebooks/group-as/asg1250e/sqlug/#Generic__BookTextView/36137;pt=36137.

Related

Alter sql server table Issue

I already created table in database. Now, I need to add "Identity" Column. Please suggest.
Create Cus(id int Pk,Name varchar2(50),Age int);
insert into Cus(id,Name,Age) values (1,'abc',12);
// here i need to add "Identity"
alter table Cus alter column id Identity(1,1)
You cannot use Alter command to add an identity to the table.
Here, you need to create dummy column and drop existing one.
Create table Cus(id int ,[Name] varchar(50),Age int);
insert into Cus(id,[Name],Age) values (1,'abc',12);
Alter Table Cus Add dummyid int identity(1,1)
Alter Table Cus Drop Column id
Exec sp_rename 'Cus.dummyid ', 'id', 'Column'
No you cannot make any column identity after creating from the query.
You have 2 options, either make it from SQL Management Studio or Create another column and copy with identity .
From Management Studio.
Step 1: Select Table design.
Step 2: Change Column properties.
Step 3: Save
Or
You need to create new column with identity.
Create column with identity `Alter table Tablename add newcol int identity(1,1)
Then copy your data from previous column to this column by setting Identity_Insert ON.
Then drop your previous column.
After that change column name by using sp_rename.
Note: But this will change the ordinal position of your column.
ANOTHER OPTION
Create new table with similar structure just make your column
identity whichever you want to be.
Copy data from your old table to new table.
Drop old table.
Change name of new table with old table.
Edit:
For case of Foreign Key relationship
If they are not so many and feasible, then you may drop the constraint.
ALTER TABLE Yourtable
DROP FOREIGN KEY FK_PersonOrder;
Then follow the above steps and recreate them at the last.
ALTER TABLE Yourtable
ADD FOREIGN KEY (yourid) REFERENCES Persons(PersonID);
Finally i got Solution,
I added new column in 'Cus' table.
alter table Cus add tempCusId int identity;
i removed FK relation in User's Table
and i updated identity values in User Table
update user set id=1 where id= 1;
I Compared Id and TempCusId. After update I removed "Pk" relation in Cus table droped Column "Id",i made "TempCusId" as a "Pk" and identity. Finally User table it self "Id" Column I made FK relation.
And if u have multiple values there than go for a "While" loop
DECLARE #NumberofRowint int=30;
DECLARE #inirow INT=23;
Declare #Grade int ;
WHILE #inirow<= #NumberofRow
BEGIN
DECLARE #ProductID INT=(select Id from [Cus] where id=#inirow)
Set #Grade=(select id from Cus where id=#ProductID)
IF(#Grade= #inirow)
BEGIN
updatetbl_Users set Id=#inirow where id=#ProductID
END
SET #inirow = #inirow + 1;
END;

ALTER COLUMN with INTEGER Datatype, NOT NULL, PRIMARY KEY, auto increment

I have a MySQL QUERY and working fine.
QUERY IS:
ALTER TABLE run
CHANGE RN_RUN_ID RN_RUN_ID INT(11) NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (RN_RUN_ID);
I tried to execute same Query and modified in MSSQL which is throwing error.
MSSQL QUERY IS:
ALTER TABLE run ALTER COLUMN RN_RUN_ID
RN_RUN_ID INT NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (RN_RUN_ID);
ERROR IS:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'AUTO_INCREMENT'.
Can you tell me what I did wrong in this query.
You cant do it directly.
See this post: Adding an identity to an existing column
First answer.
In SQL Server there is no such AUTO_INCREMENT option. Please look at the docs. The equivalent is IDENTITY.
You cannot modify a column directly to become IDENTITY. You need to create a new column on the table, or create a new table and rename it. It has some tricky parts (allowing the insert in the identity column, renaming a column, and some other things). Look this SO answer.
There are also differences on the syntax for adding a PK to a table:
ALTER TABLE run
ADD CONSTRAINT PK PRIMARY KEY (rn_run_id)
If you have acces to SQL Server Management Studio you can get the full script easyly:
add a new diagram to the database
add the table to the diagram (rigth click on the window, and use the contextual menu)
save the diagram (you can delete it later)
right click on the table and choose custom view
right click again on the table, and choose "modify custom view". Add the identity, identity initial value, identity increment, key, etc. required elements to the custom view
modify the column properties in the diagram
go to the "Table designer" menu, and choose the last option "Generate change scripts". You'll get an script which does all the changes for you. For example:
An example of doing this process (by modifying the column id of the table test):
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_test
(
id int NOT NULL IDENTITY (10, 2)
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_test SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT dbo.Tmp_test ON
GO
IF EXISTS(SELECT * FROM dbo.test)
EXEC('INSERT INTO dbo.Tmp_test (id)
SELECT id FROM dbo.test WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_test OFF
GO
DROP TABLE dbo.test
GO
EXECUTE sp_rename N'dbo.Tmp_test', N'test', 'OBJECT'
GO
COMMIT
NOTE: the name of the menu options can be different, i don't have an English SSMS at hand right now
Relevant docs:
IDENTITY
DBCC CHECKIDENT
SET IDENTITY_INSERT
ALTER TABLE

Sybase IQ: load table with autoincrement column

I need to transfer a table from database A to database B, the table has an autoincrement column. The content of the table in the new database has to be identical to the table in the original database, including the values in the autoincrement column.
The following LOAD TABLE, where col1 is the autoincrement column, doesn't work:
set identity_insert TableName on;
LOAD TABLE TableName
(col1,col2,col3)
FROM 'file.csv';
I get the following error:
Cannot insert or update Column col1: set option 'identity_insert' to the specific table name containing the identity column to be modified.
Still, I'm setting the identity_insert option. What's wrong with this command?
Please try
SET TEMPORARY OPTION IDENTITY_INSERT = 'MyTable';
This has been discussed on SCN
DEFAULTS OFF looks like it should be used as an option if you want to ovverride the default identity (autoincrement) value.
see: http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc00801.1530/doc/html/san1281564935243.html
If that doesn't work, and this is just a one time thing... the simplest way to accomplish this would be to load table into TableName_work that has no autoincrement, then insert the data into your destination via a select statement with identity_insert on.

script to add and remove auto-increment property from a column

For a sql script I'm working on, I need to programmatically remove the identity, identity seed, and identity increment for a column in an existing table, then add them back to the table at the end of the script. Does anyone have a reference or an example on how to do this?
You should do this:
SET IDENTITY_INSERT <TableName> ON
-- Do the inserting in the table with name <TableName>
SET IDENTITY_INSERT <TableName> OFF
For more details look in the MSDN.
Yes, you just do this:
SET IDENTITY_INSERT [TABLE] ON
And then back on:
SET IDENTITY_INSERT [TABLE] OFF
This will allow you to enter manual data in the identity column.
http://msdn.microsoft.com/en-us/library/ms188059.aspx

How do I add the identity property to an existing column in SQL Server

In SQL Server (in my case, 2005) how can I add the identity property to an existing table column using T-SQL?
Something like:
alter table tblFoo
alter column bar identity(1,1)
I don't beleive you can do that. Your best bet is to create a new identity column and copy the data over using an identity insert command (if you indeed want to keep the old values).
Here is a decent article describing the process in detail:
http://www.mssqltips.com/tip.asp?tip=1397
The solution posted by Vikash doesn't work; it produces an "Incorrect syntax" error in SQL Management Studio (2005, as the OP specified). The fact that the "Compact Edition" of SQL Server supports this kind of operation is just a shortcut, because the real process is more like what Robert & JohnFX said--creating a duplicate table, populating the data, renaming the original & new tables appropriately.
If you want to keep the values that already exist in the field that needs to be an identity, you could do something like this:
CREATE TABLE tname2 (etc.)
INSERT INTO tname2 FROM tname1
DROP TABLE tname1
CREATE TABLE tname1 (with IDENTITY specified)
SET IDENTITY_INSERT tname1 ON
INSERT INTO tname1 FROM tname2
SET IDENTITY_INSERT tname1 OFF
DROP tname2
Of course, dropping and re-creating a table (tname1) that is used by live code is NOT recommended! :)
Is the table populated? If not drop and recreate the table.
If it is populated what values already exist in the column? If they are values you don't want to keep.
Create a new table as you desire it, load the records from your old table into your new talbe and let the database populate the identity column as normal. Rename your original table and rename the new one to the correct name :).
Finally if the column you wish to make identity currently contains primary key values and is being referenced already by other tables you will need to totally re think if you're sure this is what you want to do :)
There is no direct way of doing this except:
A) through SQL i.e.:
-- make sure you have the correct CREATE TABLE script ready with IDENTITY
SELECT * INTO abcTable_copy FROM abcTable
DROP TABLE abcTable
CREATE TABLE abcTable -- this time with the IDENTITY column
SET IDENTITY_INSERT abcTable ON
INSERT INTO abcTable (..specify all columns!) FROM (..specify all columns!) abcTable_copy
SET INDENTITY_INSERT abcTable OFF
DROP TABLE abcTable_copy
-- I would suggest to verify the contents of both tables
-- before dropping the copy table
B) Through MSSMS which will do exactly the same in the background but will less fat-fingering.
In the MSSMS Object Explorer right click the table you need to modify
Select "design" Select the column you'd like to add IDENTITY to
Change the identity setting from NO -> YES (possibly seed)
Ctr+S the table
This will drop and recreate the table with all original data in it.
If you get a warning:
Go to MSSMS Tools -> Options -> Designers -> Table and database Designers
and uncheck the option "Prevent saving changes that require table re-creation"
Things to be careful about:
your DB has enough disk space before you do this
the DB is not in use (especially the table you are changing)
make sure to backup your DB before doing it
if the table has a lot of data (over 1G) try it somewhere else first
before using in real DB
Create a New Table
SELECT * INTO Table_New FROM Table_Current WHERE 1 = 0;
Drop Column from New Table
Alter table Table_New drop column id;
Add column with identity
Alter table Table_New add id int primary key identity;
Get All Data in New Table
SET IDENTITY_INSERT Table_New ON;
INSERT INTO Table_New (id, Name,CreatedDate,Modified)
SELECT id, Name,CreatedDate,Modified FROM Table_Current;
SET IDENTITY_INSERT Table_New OFF;
Drop old Table
drop table Table_Current;
Rename New Table as old One
EXEC sp_rename 'Table_New', 'Table_Current';
alter table tablename
alter column columnname
add Identity(100,1)

Resources