Identity specification sql как изменить

This sql server tutorial explains, Identity Column in SQL Server 2019, set identity on existing column in SQL Server, set identity column in SQL Server using query, etc.

In this article, you will learn what is Identity column in SQL Server. We will see how to use it and also see some examples.

An identity column is a column in the SQL Server table that generates keys automatically for the records in the table.

  • How to set identity column in SQL Server
  • How to set identity column in SQL Server using the query
  • How to set identity on an existing column in SQL Server
  • How to update identity column in SQL Server
  • How to insert values into a table with an identity column in SQL Server
  • How to reset identity column in SQL Server
  • Add identity to an existing column in SQL Server without dropping the column
  • Remove identity from a column in SQL Server
  • Remove identity from a column in SQL Server Example

How to set identity column in SQL Server

In this section, we will learn how to set identity column in SQL Server.

  • To create an identity column in SQL Server, you need to use the Identity Specification property while creating the table.
  • The Identity Specification property takes two values:
    • seed: The initial value from where you want to start the count of the identity column
    • increment: The increment to be done after each value of the identity column
  • Let us create a table with an identity column in SQL Server Management Studio.
  • Open SQL Server Management Studio and connect to the SQL Server database engine.
  • In the Object Explorer window, navigate to the Databases in which you want to create a table and right-click on Tables, click on New, and then Table.
how to set identity column in sql server
Create the Table
  • Now enter the column names along with their respective data types.
  • While creating the table make sure the data type of the column which you want to set as an identity column should be of integer type.
  • Click on the column which you want to set as the identity column and navigate to the Column Properties tab below.
  • Navigate to the Identity Specification option and double click to modify the column’s identity specifications.
  • Change the (Is Identity) property to Yes and specify the Identity Increment and Identity Seed and save the table.
create identity column in sql server
Set Identity Column Properties
  • Once you have set the identity column in the SQL Server table, you can try to insert rows into the table.
set identity column in sql server
Editing Table Records
  • You will notice that you are not allowed to insert values into the identity column.
  • In our example, the EmpID column is the identity column.

Thus, you might have understood how to set an identity column in a SQL Server table with the help of SQL Server Management Studio.

Read: Delete Duplicate Rows in SQL Server

How to set identity column in SQL Server using the query

In the above section, we learned to set identity columns with SQL Server Management Studio. However, you can also set an identity column with the help of a SQL query.

One can do this with the help of the IDENTITY() function. We use this function in the CREATE TABLE statement when we create a new table. We specify this function in the column that we want to set as an identity column. You can follow the steps below to set an identity column in the SQL Server table:

  • Write the query to create a new table.
  • Specify the IDENTITY() function in the CREATE TABLE statement.
CREATE TABLE <table name>(
<identity column> int IDENTITY(1,1),
<column 2> <data type>,
<column 3> <data type>,
.
.
<column n> <data type>
)
  • Once the table is created, try to insert some values.
  • Let us see an example also.
  • We have created a table IdentityTable in which we have defined the EmpID column as an identity column.
USE[master]
GO
DROP TABLE IF EXISTS dbo.TableIdentity
CREATE TABLE dbo.TableIdentity(
EmpID int IDENTITY(3,2),
EmpName nchar(20),
EmpDep nchar(10)
)
  • We defined 3 as the seed value and 2 as the increment value.
  • Now we will insert some values into the table.
USE [master]
GO
INSERT INTO dbo.TableIdentity(EmpName, EmpDep)
VALUES('Luca', 'Finance'),
	  ('Donald', 'Sales'),
	  ('George', 'Marketing'),
	  ('Mark', 'Sales')
SELECT * FROM dbo.TableIdentity
how to set identity column in sql server 2019
Created Identity Column in SQL Server
  • You can observe that we didn’t specify the values for the EmpID column but still it have values because of its identity property.
  • Also, the values started from 3 and there is an increment of 2 after every record inserted.

Let us discuss one more example. I will create another table with an identity column. Suppose the table name is dbo.Student.

USE [BackupDatabase]
GO
DROP TABLE IF EXISTS dbo.Students
CREATE TABLE dbo.Students(
Student_id int IDENTITY(10,1),
Student_name nchar(30),
Student_stream nchar(20),
City nchar(20)
)
  • This time the seed value is 10 i.e. the identity values will start from 10 and the increment value is 1.
  • Now let us insert some values into it and see the output.
USE BackupDatabase
GO
INSERT INTO dbo.Students(Student_name, Student_stream, City)
VALUES('Robert', 'Computer Science', 'Houston'),
	  ('Oliver', 'Electronics', 'Chicago'),
	  ('Benjamin', 'Electronics', 'New York'),
	  ('Peter', 'Mechanical', 'Boston')
SELECT * FROM dbo.Students
create identity column sql server
Created an identity column

You can see that we did not insert any values into the Student_id field because it is an identity column.

This is how you set an identity column in SQL Server 2019.

Read: SQL Server Create Temp Table

How to set identity on an existing column in SQL Server

In this section, will discuss the IDENTITY property of an existing column in an SQL Server table.

If you want to set IDENTITY property on an existing column in SQL Server, you have to drop the column and create it again. We will understand this method with an example.

  • Consider a table TableIdentity.
How to set identity on existing column in SQL Server
TableIdentity table
  • If we want to make the column EmpID an identity column, we will drop this column and create it again with the IDENTITY property.
  • The following query will drop the EmpID column.
USE [master]
GO
ALTER TABLE dbo.TableIdentity
DROP COLUMN EmpID
  • After dropping the column, add the same column with the ALTER statement.
  • Specify the IDENTITY option along with the seed and the increment value.
USE [master]
GO
ALTER TABLE dbo.TableIdentity
ADD EmpID int IDENTITY(3,2)
SELECT * FROM dbo.TableIdentity
  • If you observe the output, you can see that the EmpID column is now an identity column and it is having the expected key values.

Hope you have understood the things that should be kept in mind while setting the Identity property.

Read: SQL Server Row_Number

How to update identity column in SQL Server

In this section, you will learn how you can update the identity column in SQL server.

If you are saying that you want to update the identity column, you mean to say one of the two things:

  1. You want to update the Identity properties.
  2. You want to update the values in identity column of the table

We will discuss both the cases on by one.

  1. Update the Identity properties: You can update the Identity properties by using the DBCC CHECKIDENT function. Using this function, update the seed value. This means you can decide again from where you want to start the identity value count. You can do this as:
DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)
  • For example, if you have a table named Orders, and you want to give identity values from 1000, you will write the query for the table as:
DBCC CHECKIDENT('dbo.Orders', RESEED, 1000)

Read: SQL Server Add Column + Examples

How to insert values into table with identity column in SQL Server

In this section, you will learn how you can insert values into a table with the identity column in SQL Server.

When you insert values into a table having an identity column, you do not need to specify the values for the identity column. Let us understand this with an example.

  • Consider the table IdentityTable having three columns.
How to insert values into table with identity column in SQL Server
IdentityTable Table
  • In the above table, the EmpID column is the identity column.
  • If we want to insert a record in the table, we do not need to specify the value for the identity column i.e. EmpID.
USE [master]
GO
INSERT INTO dbo.IdentityTable(EmpName, EmpDep)
VALUES('Carlos','Sales')
SELECT * FROM dbo.IdentityTable
insert values into table with identity column in SQL Server
Record Inserted in a Table having Identity Column

In this section, you learned how you can insert a record in a table having an identity column. However, we didn’t discuss how we can manually insert data in the identity column. You can learn this in our IDENTITY_INSERT in SQL Server article.

How to reset identity column in SQL Server

In this section, you will learn how you can reset the identity column in a SQL Server table. There are two ways in which you would want to do this.

One method is to drop the column and create it again specifying the Identity property and deciding the seed and the increment value. You can learn this thing in the above How to set identity on existing column in SQL Server section.

The other method is to use the DBCC utility. Using this utility you can define the new value from where you want to start the identity values. This method is suitable when you have a certain number of records in your table and you want to change the initial seed value of the Identity property.

  • You can use the DBCC CHECKIDENT() function to set the new seed value as:
DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)
  • For example, if you have the IdentityTable table and you have already assigned the identity values from 1 to 10.
How to reset identity column in SQL Server
IdentityTable Table
  • If you want to start the next count from 100, you will write the query as:
DBCC CHECKIDENT('dbo.Student', RESEED, 99)
  • After running this query, your count will start from 100 if you insert any record into it.
  • Let us try to insert a record.
USE [master]
GO
INSERT INTO dbo.IdentityTable(EmpName, EmpDep)
VALUES('Carry','Marketing')
SELECT * FROM dbo.IdentityTable
reset identity column in SQL Server
Indentity Value Started from 100

Hence, you might have understood how you can reset the identity column in a SQL Server table.

Read: SQL Server drop table if exists

Add identity to existing column in SQL Server without dropping column

In SQL Server, you have to define the identity column when you create the table or you add a column in the existing table.

You cannot add the Identity property to an existing column without dropping it. However, you can learn how you can add the Identity property to an existing column in the above sections of this article.

Remove identity from column in SQL Server

In this section, we will discuss the removal of the Identity property from a column in SQL Server.

You cannot remove the identity property directly from the column. If you have defined the IDENTITY when you created the table, you cannot remove it. However, there are some alternatives to do that.

  1. Drop the column and add it again with the ALTER statement. You can create the column again without mentioning the identity column. It is a very feasible method that you would like to use mostly.
  2. Drop the whole table and create it again. Use this method if you have the backup of the data and the size is also small so that it is feasible to create the table again.
  3. Create a duplicate table and change the meta-information about the tables. You can also use this method. In this method, you do not have to do much.
    1. Create a new table with the same specifications.
    2. Run the following query:
      • ALTER TABLE [Original Table] SWITCH TO [New Table]
    3. This query will interchange the metadata of both tables.
    4. Your original table will have no data. All that data will be transferred to the new table.
    5. Drop the old table and rename the new table to the old table name.

Remove identity from a column in SQL Server Example

In the above section, we discussed how we can remove Identity property from a column in SQL Server. We will see an example of the above method in detail.

  • We have a table named IdentityTable. It has an identity column EmpID.
  • We will create a new table named IdentityTable1 having exactly the same structure but no identity column defined.
  • Then we will interchange their meta-information.
ALTER TABLE dbo.IdentityTable SWITCH TO dbo.IdentityTable1
  • After running this query, you verify that IdentityTable has no data in it and all the data is transferred to the IdentityTable1.
  • After the data transfer, drop the table IdentityTable.
  • Then rename the IdentityTable to IdentityTable1 using the stored procedure sp_rename.
EXEC sp_rename 'IdentityTable1', 'IdentityTable'
  • Now you have completed the procedure and you will have the same table with all your data conserved and the identity property is also removed.

You may like the following database tutorials:

  • MySQL vs SQL Server – Key Differences in Details
  • How to export data from SQL Server to Excel
  • SQL Server Substring Function [9 Examples]
  • Advanced Stored Procedure Examples in SQL Server
  • How to execute function in SQL with parameters
  • How to set identity column in SQL Server
  • How to set identity column in SQL Server using a query
  • How to set identity on an existing column in SQL Server
  • How to update identity column in SQL Server
  • How to insert values into a table with an identity column in SQL Server
  • How to reset identity column in SQL Server
  • Add identity to an existing column in SQL Server without dropping a column
  • Remove identity from a column in SQL Server
  • Remove identity from a column in SQL Server Example

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

Вопрос:

Это может быть глупый вопрос, но почему я не могу изменить спецификацию Identity или (Is Identity) с “Нет” на “Да”?

Ответ №1

Проверьте тип данных столбца.

Если это varchar, вы не можете изменить столбец идентификаторов.

Чтобы изменить столбец идентификатора, он должен иметь тип данных int.

Ответ №2

Вы не можете изменить свойство IDENTITY столбца в существующей таблице. Вы можете добавить новый столбец с свойством IDENTITY, удалить старый столбец и переименовать новый столбец со старым именем столбца.

Конечно, то, что происходит тогда (для некоторых людей), заключается в том, что им не нравится тот факт, что новый столбец появляется “в конце” списка столбцов (хотя вы не должны заботиться о позициях столбцы – вы всегда должны использовать их имена). В этом случае вам нужно сделать один и тот же трюк, но на более высоком уровне – создать новую таблицу (с изменением определения столбца), скопировать данные из старой таблицы в новую, удалить старую таблицу и переименовать новую.

Я думал, что SSMS все еще пыталась притвориться, что это возможно, сделав второй трюк за кулисами.

Ответ №3

Вы можете отключить опцию “предотвратить сохранение изменений, требующих повторного создания таблицы”
но это настоятельно не рекомендуется с помощью msdn.

чтобы сделать это:

Инструменты → Опции → Дизайнеры
Отмените выбор: “предотвратите сохранение изменений, требующих повторного создания таблицы”

Ответ №4

Также проверьте, чтобы в столбце не было значения по умолчанию или привязки.

Ответ №5

Удалить значение по умолчанию или привязку.

Ответ №6

Следуя вышеприведенному комментарию Damien_The_Unbeliever, вы можете отредактировать порядок столбцов в интерфейсе проектирования Visual Studio.

Мне удалось сделать это успешно. Для подтверждения выполните следующие шаги:

  • Добавить новый столбец с свойством IDENTITY
  • удалить старый столбец,
  • Переименуйте новый столбец со старым именем столбца.
  • (Необязательно) Переупорядочить столбцы, чтобы иметь столбец IDENTITY из Visual Studio.
SQL Server
SQL 2005+

The twelfth part of the SQL Server Programming Fundamentals tutorial describes identity columns. By applying an identity specification to a numeric column, the column’s value is defaulted to a new value for every row inserted into the table.

What is an Identity?

An identity can be thought of as a special form of default value that can be applied to a column in a table. When applied to a numeric column, a new integer value is inserted automatically for each new data row. However, unlike with default constraints, a value cannot normally be specified to override the identity value. In other database management systems an identity may be called an autonumber or automatically incrementing value.

The identity column value is selected based upon the identity specification, which consists of a seed and an increment value. The first row inserted takes the value specified in the seed. Subsequent rows use a number that is calculated by adding the increment value to the previous value. Commonly the seed and increment values are both set to one to give a natural sequence. It is quite acceptable, however, to start with a seed that is negative, potentially doubling the number of available values that may be generated.

An identity can only be added to a single column within any table. Additionally, they can only be added to numeric columns that store integer values. These include TinyInt, SmallInt, Int and BigInt columns. You can also apply an identity to numeric or decimal columns if the scale for the data type is set to zero.

Identity columns are often used as surrogate primary keys as they can be used to generate unique values when used correctly. However, it is possible that an identity can generate a duplicate value if existing rows are within the range of an identity specification. Additionally, you should not rely on identities to provide a sequential set of numbers. It is possible that identity values can be skipped following an aborted or failed insert. Also, the sequence will be broken, leaving holes in the range, if rows are deleted from the table.

Adding an Identity to a Column

There are several ways in which an identity can be applied to a column in a table. In this article we will consider two options: adding identities using the SQL Server Management Studio graphical user interface tools and creating them using Transact-SQL statements.

In the article we will add identity specifications to columns in the JoBS tutorial database. This database has been created over the course of this tutorial. If you have not followed the tutorial, download and run the scripts using the link at the top of this page to create the database and sample data. You can also use this script if you wish to refresh your copy of the database and add items from the previous article.

Adding an Identity Specification Using SQL Server Management Studio

The easiest manner of defining an identity in a database is using the table designer in SQL Server Management Studio (SSMS). An identity can be added to a table when it is first created or at a later time, even if the table already contains information.

The Contracts table in the Jobs database contains an integer-based surrogate primary key that is an ideal candidate for using an identity column. To create this identity, open the table designer for the table and select the first row in the grid. This row represents the ContractNumber column.

Once the row is selected, the column properties will be updated to show, and allow editing of, the column settings. Within the «Table Designer» section you should see the «Identity Specification» option. This option will initially be set to No. Using the + icon to the left of the property, expand the grid to show the three available identity options:

  • (Is Identity). This property determines whether the column uses an identity. When set to No, the two other properties may not be modified.
  • Identity Increment. This value is added to the previous identity value each time a new row is added to the table. The resultant value is stored in the column. The value can be a positive or negative value but may not be zero.
  • Identity Seed. This value is the number that will be used in the identity column for the first row inserted into the table.

In this case, we want the first contract number to be one and we want this number to increase by one each time we insert a new row. To apply these settings, set (Is Identity) to Yes and set both the seed and increment values to 1. To retain the changes, save the table design and close the designer window.

Inserting Rows

Once the identity value has been applied, you can add new rows to the table using SSMS. Right-click the Contracts table in the Object Explorer and choose «Open Table» from the menu that appears. The table’s twenty-one rows will be visible

Note that the numbers in the ContractNumber column are already using the values from one to twenty-one. These values were added manually by the JoBS database script. However, we can now add a new row to see the result of the identity column.

Move the cursor to the blank row at the bottom of the grid. Leave the first cell in this row blank, then add the following values to the remaining cells:

ContractNumber CustomerAddressId RenewalDate RenewAutomatically ContractValue
(Leave Blank) 5 (Leave Blank) (Leave Blank) 49.99

After typing all of the information, press the Tab key to move to the next row. You should see that the ContractNumber column is automatically populated. However, sometimes the column is not immediately updated in the grid and incorrectly displays «NULL». If this is the case, refresh the grid by pressing Ctrl-R. You will see that SQL Server has recognised that some of the identity range has already been used and has therefore set the contract number for the new row to twenty-two.

You can, of course, use Transact-SQL statements to insert data into the table. When creating new rows, you should not attempt to insert a value into the identity column, as this will cause an error.

10 September 2008

Понравилась статья? Поделить с друзьями:
  • Ibexpert проверка базы данных на ошибки
  • Ibexpert sql error code 104
  • Ibexpert gds32 dll ошибка
  • Iaudioclient initialize ошибка aimp
  • Iastorvd sys ошибка при установке windows 7