Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into a table with just one IDENTITY column (SQL Express)

Pretty much the same as this question.

But I can't seem to get this to work with SQL Server Express in Visual Studio 2008.

Same Table layout, One column with identity and primary key.

like image 990
Thomas Sandberg Avatar asked Sep 01 '09 12:09

Thomas Sandberg


People also ask

How will you insert data into a table with identity column in SQL Server?

To manually insert a new value into the Id column, we first must set the IDENTITY_INSERT flag ON as follows: SET IDENTITY_INSERT Students ON; To set the IDENTIT_INSERT flag ON we need to use the SET statement followed by the flag name and the name of the table.

Can you implicitly insert an identity column in a table?

Yes. That's all you need to do. SET ON, write your code, SET OFF at the end.

How can I insert one column values in a table in SQL?

INSERT INTO Syntax 1. Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...)

Can we insert in only one column in SQL?

To insert values into specific columns, you first have to specify which columns you want to populate. The query would look like this: INSERT INTO your_table_name (your_column_name) VALUES (the_value);


1 Answers

 INSERT INTO dbo.TableWithOnlyIdentity DEFAULT VALUES

This works just fine in my case. How are you trying to get those rows into the database? SQL Server Mgmt Studio? SQL query from .NET app?

Running inside Visual Studio in the "New Query" window, I get:

The DEFAULT VALUES SQL construct or statement is not supported.

==> OK, so Visual Studio can't handle it - that's not the fault of SQL Server, but of Visual Studio. Use the real SQL Management Studio instead - it works just fine there!

Using ADO.NET also works like a charm:

using(SqlConnection _con = new SqlConnection("server=(local);
                             database=test;integrated security=SSPI;"))
{
    using(SqlCommand _cmd = new SqlCommand
            ("INSERT INTO dbo.TableWithOnlyIdentity DEFAULT VALUES", _con))
    {
        _con.Open();
        _cmd.ExecuteNonQuery();
        _con.Close();
    }
}   

Seems to be a limitation of VS - don't use VS for serious DB work :-) Marc

like image 60
marc_s Avatar answered Oct 19 '22 04:10

marc_s