86

I have a table Administrator with only one column, adminId which is the primary-key. Because of business rules it has to be this way.

I'd like to understand once and for all how I can write stored procedures that insert values in tables like this. I am using SQL Server and T-SQL and tried using SCOPE_IDENTITY() but that doesn't work since the table has INSERT_IDENTITY to false or off.

I'd really like to not insert a dummy value just to be able to insert a new row. Thanks!

Gray
  • 115,027
  • 24
  • 293
  • 354
Phil
  • 3,934
  • 12
  • 38
  • 62
  • 1
    To clarify: your question is "how to insert rows in a SQL Server table with a single IDENTITY column"? – gbn Nov 07 '10 at 12:51
  • 2
    For people landing here, this has been asked before and the correct answer is here: http://stackoverflow.com/questions/850327/how-to-insert-into-a-table-with-just-one-identity-column – BJury Nov 06 '13 at 12:03

3 Answers3

144

If you have one column that is an IDENTITY, just do this

INSERT MyTable DEFAULT VALUES;  --allows no column list. The default will be the IDENTITY
SELECT SCOPE_IDENTITY();

If you don't have identity, then can you set it? This is the best way.. and use the SQL above.

If not, you want to insert a new row

INSERT MyTable (admidid)
OUTPUT INSERTED.admidid --returns result to caller
SELECT ISNULL(MAX(admidid), 0) + 1 FROM MyTable

Notes:

  • Under high loads the MAX solution may fail with duplicates
  • SCOPE_IDENTITY is after the fact, not before
  • SCOPE_IDENTITY only works with an IDENTITY column. Ditto any idiocy using IDENT_CURRENT
  • The output clause replaces SCOPE_IDENTITY for the MAX solution
gbn
  • 422,506
  • 82
  • 585
  • 676
1

You need to add the IDENTITY_INSERT to your select statement:

SET IDENTITY_INSERT MyTable ON

INSERT INTO MyTable
(AdminCol)

SELECT AdminColValue

 FROM Tableb

When you're done, make sure you remember to

SET IDENTITY_INSERT MyTable OFF

Here's a good description of how it works from BOL: http://msdn.microsoft.com/en-us/library/aa259221(SQL.80).aspx

gbn
  • 422,506
  • 82
  • 585
  • 676
DataWriter
  • 1,010
  • 1
  • 10
  • 25
  • Am I supposed to do it like this: SET IDENTITY_INSERT Administrator ON INSERT INTO Administrator (SCOPE_IDENTITY()) SET IDENTITY_INSERT Administrator OFF ? – Phil Nov 07 '10 at 12:34
  • Yes. That's all you need to do. SET ON, write your code, SET OFF at the end. – DataWriter Nov 07 '10 at 15:08
  • I don't think this is the right answer. If it's an identity column, you shouldn't be adding values to it. The accepted answer is the correct answer. – Mmm Nov 11 '15 at 17:12
0

@Phil: Don't you mean your table has two(2) columns, the autoincrementing PK column and an AdminName column? If it only has one column where the AdminName goes, the AdminName is the PK and you cannot autoincrement a string, of course. Do the business rules expect you to make a fully-qualified Windows username the primary key? That would be viable and make sense, because then you wouldn't need an alternate unique index on the AdminName column.

But if your table has two columns, not one:

In SQLServer the autoincrement is part of the table/column definition. You define the column as an integer and then also make it an identity column, specifying the increment, usually 1, but it could be 2 or 5 or 10 or whatever. To insert a row, you simply insert the other column(s) value(s) and do nothing with the PK column:

insert into T
(foo)   -- column(s) list
values('bar') -- values list

Your stored proc that does the insert can make SCOPE_IDENTITY a RETURN value or SCOPE_IDENTITY can be passed back to the client as an OUT parameter.

P.S. SCOPE_IDENTITY() returns the most recently generated autoincremented identity value in the current scope; it does not generate the next identity value.

EDIT:

Presumably, your Administrators table contains a set of administrators. But if it has no columns whatsoever other than the integer primary key column, there is no way to identify the administators; the only thing you can do is distinguish them from each other. That doesn't get you very far at all. But if your Administrator table had either of the following structures:

ID   INTEGER PRIMARY KEY AUTOINCREMENT
windowsusername   varchar(50)  (unique index)

OR

windowsusername varchar(50) primary key

you would be able to reference the Administrator's table from other tables, and the foreign keys would be MEANINGFUL. And that's precisely what a table consisting of a single integer column lacks -- meaning.

Having two columns, you could then have a stored procedure do this:

insert into Administrators
(windowsusername)
values('mydomain\someusername');
return SCOPE_IDENTITY();

and your client-program would get back as a return value the autoincremented id that had been autogenerated and assigned to the newly inserted row. This approach is the usual practice, and I would go so far as to say that it is considered "best practice".

P.S. You mention that you didn't know how to "insert a value" if you "didn't have anything to insert". There's a contradiction there. If you have nothing to insert, why insert? Why would you create, say, a new CUSTOMER record if you know absolutely nothing about the customer? Not their name, their city, their phone number, nothing?

Tim
  • 5,371
  • 3
  • 32
  • 41
  • 2
    My table has ONE column, adminId, which is an incremental int value – Phil Nov 07 '10 at 13:14
  • That is the strangest design I've ever seen, and I've been in the business for over 20 years and have seen some strange things in my day. So your question is, How do you insert into a table that contains only a primary key column defined as an autoincrementing identity column, when the table contains that PK column and only that PK column, no other columns.. – Tim Nov 07 '10 at 13:52
  • So what's the downvote for? A factual error somewhere or for expressing an opinion about the lack of merit of the design? – Tim Nov 07 '10 at 15:16
  • Yes, the design is strange, I agree. It is probably because this table will expand in the future. I downvoted because you answered how to do it with two columns and not one. My problem was that I didn't know how to insert a value when I didn't have anything to insert. If you feel I've misunderstood your answer; please explain and I'll upvote if I understand what you mean. – Phil Nov 07 '10 at 17:50
  • OK, I will append to my previous answer since the site is not letting me add another answer. – Tim Nov 07 '10 at 20:56
  • 1
    Just to clarify the reasoning behind the DB-design. We have users in one table. If there is a has-relation between users and administrators; they are treated as admins. There is nothing more to keep in the Admin-table than the actual unique id. The "real" data is in the user-table and the has-relation (with timestamps and who granted etc). – Phil Aug 04 '11 at 16:57
  • 1
    @Phil: So you're using a table and a foreign key relationship to express what a simple boolean/bit column could do. You may not be able to add such a bit column to your table and have to come up with some workaround. `But an autoincrementing integer whose autoincrementation must be disabled is a poor solution.` All you need is a parallel table with a one-to-one relationship to the users table and in that table you create a bit column. When that column is true, it means the user has-admin. Clean. Standard. Design. – Tim Aug 06 '11 at 11:25