Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short Sql insert Statement?

In MySql I could have a table with an auto increment column and insert that way:

INSERT INTO tbl VALUES(null, "bla", "bla");

Is there any way to do this with Microsoft SQL Server Express?

Instead of this:

INSERT INTO tbl(`v1`, `v2`) VALUES ("bla", "bla");  

Thanks

like image 673
Adir Avatar asked Jun 25 '26 22:06

Adir


1 Answers

In Sql Server, you do not need to specify a value for identity columns (I'm guessing this is what the null in mysql is doing).

So, the short syntax for inserting into your table would be:

Insert Into tbl Values('bla', 'bla')

This works regardless of whether the column is declared to be the primary key of the table and also works for any position of the column in the table. That is, even if the column is in the middle as shown below:

Create Table tbl (
    [Col1] [varchar](50) NULL,
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Col2] [varchar](50) NULL
)

Sql Server will still quite happily interpret the insert statement and take care of the identity insert.

As other posters have mentioned, in Sql Server you actually need to issue the Set Identity_Insert tbl On command to be able to specify a value for identity columns.

like image 191
David Hall Avatar answered Jun 27 '26 14:06

David Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!