簡體   English   中英

如何在 SQL 中正確設置默認值?

[英]How to set default values properly in SQL?

我有一個根本不應該有任何 NULL 值的表。 當我設置 NOT NULL 約束時,它不允許該語句並且它因約束錯誤而失敗。 僅當插入語句中未引用該列時,才會發生默認約束。

我們怎樣才能解決這個問題? 如果插入語句的任何列具有 NULL 值,則必須采用 DEFAULT 值而不是 NULL 值。

create table temp1 (col0 int, col1 int default 0);
insert into temp1 (col0) values (1); --> col0 -> 1 and col1 ->0
insert into temp1 (col0,col1) values (1,NULL); --> col0 -> 1 and col1 -> NULL (I would expect a 0 here instead of NULL)
alter table temp1 (add column col2 int not null default 0); --> col2 -> 0 for all the existing rows
insert into temp1 (col0) values (2);  --> col0 -> 2 and col1 ->0 and col2-> 0
select * from temp1;

COL0 |COL1   |COL2
1    |0      |0   
1    |(null) |0   
2    |0      |0   

將 NULL 轉換為插入的列的默認值不是標准 SQL 的一部分。

正如您所觀察到的,您可以從 insert 語句中省略該列,但這與插入 NULL 值不同。 相反,實際上,列的 DEFAULT 的默認值是 NULL(SQL92 13.8 一般規則 4b); 這就是為什么如果沒有明確定義默認值,插入默認值會給出 NULL。

您也可以包含該列並使用關鍵字 DEFAULT(SQL92 7.1 一般規則 2)。 WX2 目前不支持這種語法,但Kognitio計划在即將推出的 8.2 版中添加它。

insert into temp1 (col0, col1) values (1, DEFAULT);

該標准只允許您使用上面顯示的 DEFAULT,而不是在復合表達式或插入選擇語句中。

-- NOT VALID IN STANDARD SQL!
insert into temp1 (col0, col1) values (1, case when ... then 1 else DEFAULT end);

-- NOT VALID IN STANDARD SQL!
insert into temp1 (col0, col1) select C1, DEFAULT from ...;

您可以使用 COALESCE() 函數解決此問題。

insert into temp1 (col0, col1) select E1, COALESCE(E2, 0) from ...;

其他數據庫通常也不允許將 NULL 轉換為默認值:請參閱SQL ServerMySQLPostgresFirebird 的類似問題。 Oracle 確實有一個非標准語法來創建帶有DEFAULT ON NULL 的表列,這可以滿足您的需求。

(Kognitio 可能會在復合表達式中添加 DEFAULT 或在未來版本中添加 DEFAULT ON NULL 作為擴展。)

暫無
暫無

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

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