Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm curious how a query would look like in sql where you add a new row similar to using recordset.addnew.

So far I haven't had the need to manually insert a new row in my table but I realized that I'm not really sure how to insert a new row in to a table with an identity column that's incremented for each new row.

The code in an VB6 program first runs a query that looks like this:

SQL
select top 1 from table


and then there is a recordset called rs.

VB
rs.addnew
rs!attribute = somevalue
rs!attribute1 = somevalue
...
rs.update


What's a good way to replicate this in a single query if I manually would like to add a new row and get the correct value in the identity column?


Follow up after trying the posted answer and it worked on one table but not on this that I created recently.

SQL
CREATE TABLE [dbo].[HyllaDirekt] (
    [Id]      INT          NOT NULL,
    [Temponr] NUMERIC (18) NOT NULL,
    [Platsid] BIGINT       NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);


CSS
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'Id', table 'synpro.dbo.HyllaDirekt'; column does not allow nulls. INSERT fails.
The statement has been terminated.


Is generated when inserting into this column using
SQL
insert into hylladirekt(temponr,platsid)


Changing the definition to this fixed it:

SQL
CREATE TABLE [dbo].[HyllaDirekt] (
    [Id]      NUMERIC (18)   IDENTITY (1, 1) NOT NULL,
    [Temponr] NUMERIC (18) NOT NULL,
    [Platsid] BIGINT       NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
Posted
Updated 13-Aug-15 21:21pm
v3

1 solution

You would use an INSERT statement.

Something like
SQL
INSERT INTO TableName (Column1, Column2, ...)
VALUES (value1, value2, ...)


For more information, have a look at INSERT[^]

Concerning the identity, if the identity is defined in the table creation, you just omit that column in the INSERT statement.
 
Share this answer
 
Comments
Member 11683251 14-Aug-15 3:03am    
Thanks, it worked when I tested on one existing table but not on another one, posted the table definition, can you see what I missed?
Wendelius 14-Aug-15 3:13am    
What is the statement that didn't work?
Wendelius 14-Aug-15 3:16am    
Also please post the error message you got (if any)
Member 11683251 14-Aug-15 3:23am    
Added the message but I did manage to fix it by changing the definition by looking at how the other tables were created. Not entirely sure why it works thou.

Thanks for tanking your time helping me. :)
Wendelius 14-Aug-15 3:27am    
Det var ett nöje :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900