How do I create a serial number in SQL for INSERT?

c#, database, sql, sql-server, t-sql

Solution

Use `IDENTITY`:

CREATE TABLE YourTable
(
    ID INT IDENTITY
)

Each time you insert a new record SQL Server will take care of incrementing this value for you (no two records will have the same number, it is unique).

Problem

I'm saving data to a table, but I also need a column with a serial number. How do I do that? (I'm doing this in C#, perhaps it matters.) This must be pretty simple, but googling hasn't been successful. EDIT: I don't want to just save an integer. I want to give SQL a command to create it when saving, because if I create an integer and save it between creating it and saving it – another query might try to save the same number at the same time, and I'll get two entries with the same number.)

Original source