【问题标题】:How to Insert auto increment ID where column not auto_increment如何在列不是 auto_increment 的情况下插入自动增量 ID
【发布时间】:2015-03-15 16:48:08
【问题描述】:

我正在尝试在 ID 为 int 的表中插入一些数据。 Id 是唯一的,我不知道为什么这个软件的开发者没有将此字段设置为 auto_increment

所以通常这会起作用,因为使用 auto_increment 我会排除 ID 它会自动填充。

Insert into [dbtest].[dbo].[tArtikelAttribute]
([kArtikel] ,[cName] ,[cValue])
Select [kArtikelAttribute], kArtikel, 'han', cHan 
from [dbtest].[dbo].[tartikel] Where cHan is not NULL

我收到此错误

消息 515,第 16 级,状态 2,第 2 行 值 NULL 不能插入到 kArtikelAttribute 列 dbtest.dbo.tArtikelAttribute 表中。该列不允许空值。插入错误。声明已结束

表 [tArtikelAttribute] 是
ID (PK, int, Not Null)
kartikel (int, null)
cname (varchar(255), null)
cvalue (varchar(4000), null)

我不想更改字段属性,因此我不会干扰软件功能 有人知道怎么做吗?

谢谢

【问题讨论】:

    标签: sql insert auto-increment


    【解决方案1】:

    我无法将此作为评论发布,因为我没有足够的声誉来执行该操作。

    尝试查看此链接:SQL Server, How to set auto increment after creating a table without data loss?

    可能会有所帮助。

    【讨论】:

      【解决方案2】:

      我找到了答案,感谢您使用 row_number() 的帮助

       Insert into [eazybusiness].[dbo].[tArtikelAttribute]
        ([kArtikelAttribute], [kArtikel] ,[cName] ,[cValue])
        Select (Select max([kArtikelAttribute]) 
        from [eazybusiness].[dbo].[tArtikelAttribute]) 
            + ROW_NUMBER() OVER (ORDER BY kArtikel), kArtikel, 'han', cHan 
        from [eazybusiness].[dbo].[tartikel] Where cHan is not NULL
      

      【讨论】:

        猜你喜欢
        • 2010-11-06
        • 2012-10-30
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 2013-07-03
        • 2016-09-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多