簡體   English   中英

沒有身份插入列

[英]Insert into column without having IDENTITY

我有桌子

CREATE TABLE [misc]
(
    [misc_id] [int] NOT NULL,
    [misc_group] [nvarchar](255) NOT NULL,
    [misc_desc] [nvarchar](255) NOT NULL
)

misc_id [int] not null應該是IDENTITY (1,1)但不是,現在我遇到了問題

使用插入到該表中的簡單表格,但是由於misc_id正在尋找用戶無法訪問的號碼,除非他們有權訪問數據庫。

我知道一個選項是創建另一個使其成為IDENTITY(1,1)並復制該數據。

還有另一種方法可以解決這個問題嗎?

INSERT INTO misc (misc_group, misc_desc)
VALUES ('#misc_group#', '#misc_desc#')

我有SQL Server 2012

將int列更改為標識可能會導致問題,因為默認情況下,如果不使用set identity_insert命令,則無法將值插入到Identity列中。 因此,如果您已有將值插入到Identity列中的代碼,它將失敗。 但是,允許SQL Server插入值(將其更改為Identity列)要容易得多,因此我將misc_id更改為Identity列,並確保沒有程序將值插入misc_id。

如果不能更改表,則可以嘗試插入另一個具有最新[misc_id]值的表,因此,每當在表中插入新記錄時,都將檢索該值,將其添加1,並將其用作新表。 ID。 只是不要忘了之后要更新表。

您應該使用所需的標識列重新創建表。 以下語句將使您接近。 在您遷移數據時,SQL Server會自動將表的標識字段調整為MAX(misc_id)+ 1。

您顯然需要停止嘗試在新記錄中插入misc_id。 插入記錄后,您需要檢索SCOPE_IDENTITY()列。

-- Note: I'd recommend having SSMS generate your base create statement so you know you didn't miss anything.  You'll have to export the indexes and foreign keys as well.  Add them after populating data to improve performance and reduce fragmentation.
CREATE TABLE [misc_new]
(
    [misc_id] [int] NOT NULL IDENTITY(1,1),
    [misc_group] [nvarchar](255) NOT NULL,
    [misc_desc] [nvarchar](255) NOT NULL
    -- Todo: Don't forget primary key but can be added later (not recommended).
)
GO

SET IDENTITY_INSERT misc_new ON;

INSERT INTO misc_new
(
    [misc_id],
    [misc_group],
    [misc_desc]
)
SELECT
    [misc_id],
    [misc_group],
    [misc_desc]
FROM misc
ORDER BY misc_id;

SET IDENTITY_INSERT misc_new OFF;
GO

EXEC sp_rename 'misc', 'misc_old';
EXEC sp_rename 'misc_new', 'misc';
GO

MSSQL 2012您可以使用SEQUENCE對象:

CREATE SEQUENCE [dbo].[TestSequence] 
 AS [BIGINT]
 START WITH 1
 INCREMENT BY 1
GO

改變1START WITH 1MAX value for [misc_id] + 1

用法:

INSERT INTO misc (misc_id, misc_group, misc_desc)
VALUES (NEXT VALUE FOR TestSequence, '#misc_group#','#misc_desc#')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM