visual-studio 如何插入只有一个 IDENTITY 列的表(SQL Express)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1362148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 10:56:43  来源:igfitidea点击:

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

sqlvisual-studiotsqlsql-server-expressidentity

提问by Thomas Sandberg

Pretty much the same as thisquestion.

这个问题差不多。

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

但我似乎无法让它与 Visual Studio 2008 中的 SQL Server Express 一起使用。

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

相同的表布局,一列具有标识和主键。

回答by marc_s

 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?

这在我的情况下工作得很好。您如何尝试将这些行放入数据库?SQL Server 管理工作室?来自 .NET 应用程序的 SQL 查询?

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

在“新查询”窗口中的 Visual Studio 中运行,我得到:

The DEFAULT VALUES SQL construct or statement is not supported.

不支持 DEFAULT VALUES SQL 构造或语句。

==> 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!

==> 好的,所以 Visual Studio 无法处理它 - 这不是 SQL Server 的错,而是 Visual Studio 的错。改用真正的 SQL Management Studio - 它在那里工作得很好!

Using ADO.NET also works like a charm:

使用 ADO.NET 也很有魅力:

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

似乎是 VS 的限制 - 不要将 VS 用于严肃的 DB 工作:-) Marc

回答by DRapp

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

不要试图依赖一些关于“DEFAULT VALUES”作为关键字的语法,让引擎帮助你...如何明确地尝试设置一个值,例如

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.

因此,即使您只准备一个字段,本机引擎的新记录应该用它们各自的默认值填充其余的字段。