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

只谈情不闲聊 提交于 2019-11-30 01:09:48

问题


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.


回答1:


 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




回答2:


Instead of trying to rely on some syntax about "DEFAULT VALUES" as the keyword, let the engine help you with that... How about explicitly trying to set ONE of the values, such as

insert into YourTable ( PickOneField ) values ( "whatever" )

So, even though you are only preping ONE field, the new record by the native engine SHOULD populate the REST of them with their respective default values.



来源:https://stackoverflow.com/questions/1362148/how-to-insert-into-a-table-with-just-one-identity-column-sql-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!