SQL Server 的「無法將 NULL 插入列 'id'」錯誤:綜合指南
將資料插入 SQL Server 資料庫需要提供所有列的值,尤其是主鍵。 如果列被指定為 NOT NULL
並且缺少預設值,則嘗試插入 NULL
將觸發錯誤。
場景:插入角色表
考慮這個 SQL 語句:
<code class="language-sql">INSERT INTO role (name, created) VALUES ('Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())</code>
這會嘗試在 role
表中新增兩行(包含 name
和 created
列 – 後者俱有預設時間戳)。 主鍵列 id
被省略。
錯誤分解
SQL Server 要求明確主鍵值或自動產生。 由於 id
未指定且沒有預設值,因此 SQL Server 會指派它 NULL
。 但是,id
被定義為 NOT NULL
,從而防止 NULL
插入。 結果錯誤訊息是:
<code>Msg 515, Level 16, State 2, Line 1 Cannot insert the value NULL into column 'id', table 'CMT_DEV.dbo.role'; column does not allow nulls. INSERT fails. The statement has been terminated.</code>
解決方案:自動遞增來救援
解決方案是確保id
始終收到有效值。 最常見的方法是使用自動增量:
使用 SQL Server Management Studio (SSMS):
role
表。 id
列並存取其列屬性。 這將 id
配置為為每個新行自動遞增,從而消除手動主鍵規格。
以上是為什麼我在 SQL Server 中收到「無法將 NULL 值插入列 'id'」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!