Transact-SQL 参考

SET ANSI_NULL_DFLT_ON

当数据库的 ANSI null default选项为 false 时,更改会话行为以替代新列的默认为空性。有关设置 ANSI null default 值的更多信息,请参见 sp_dboption设置数据库选项

语法

SET ANSI_NULL_DFLT_ON {ON | OFF}

注释

当在 CREATE TABLE 和 ALTER TABLE 语句中没有指定列的为空性时,该设置仅影响新列的为空性。当 SET ANSI_NULL_DFLT_ON 为 ON 时,如果没有显式指定列的为空性状态,则使用 ALTER TABLE 和 CREATE TABLE 语句创建的新列可以使用空值。SET ANSI_NULL_DFLT_ON 对使用显式 NULL 或 NOT NULL 创建的列无效。

不能将 SET ANSI_NULL_DFLT_OFF 和 SET ANSI_NULL_DFLT_ON 同时设置为 ON。如果将一个选项设置为 ON,则将另一个选项设置为 OFF。因此,可以或者将 ANSI_NULL_DFLT_OFF 或 ANSI_NULL_DFLT_ON 设置为 ON,或者将二者都设置为 OFF。如果有一个选项为 ON,则该选项(SET ANSI_NULL_DFLT_OFF 或 SET ANSI_NULL_DFLT_ON)生效。如果两个选项都设置为 OFF,则 Microsoft® SQL Server™ 将使用 sp_dboption ANSI null default 选项值。

为使 Transact-SQL 脚本在含有不同为空性设置的数据库中获得最可靠的操作,最好始终在 CREATE TABLE 和 ALTER TABLE 语句中指定 NULL 或 NOT NULL。

SQL Server ODBC 驱动程序和用于 SQL Server 的 Microsoft OLE DB 提供程序在连接时自动将 ANSI_NULL_DFLT_ON 设置为 ON。对来自 DB-Library 应用程序的连接,SET ANSI_NULL_DFLT_ON 默认为 OFF。

当 SET ANSI_DEFAULTS 为 ON 时,将启用 SET ANSI_NULL_DFLT_ON。

SET ANSI_NULL_DFLT_ON 的设置是在执行或运行时设置,而不是在分析时设置。

权限

SET ANSI_NULL_DFLT_ON 权限默认授予所有用户。

示例

下例显示 SET ANSI_NULL_DFLT_ON 使用 ANSI null default 数据库选项的两个设置时的效果。

USE pubs
GO
-- The code from this point on demonstrates that SET ANSI_NULL_DFLT_ON
-- has an effect when the 'ANSI null default' for the database is false.
-- Set the 'ANSI null default' database option to false by executing
-- sp_dboption.
EXEC sp_dboption 'pubs','ANSI null default','false'
GO
-- Create table t1.
CREATE TABLE t1 (a tinyint) 
GO 
-- NULL INSERT should fail.
INSERT INTO t1 (a) VALUES (null)
GO
-- SET ANSI_NULL_DFLT_ON to ON and create table t2.
SET ANSI_NULL_DFLT_ON ON
GO
CREATE TABLE t2 (a tinyint)
GO 
-- NULL insert should succeed.
INSERT INTO t2 (a) VALUES (null)
GO
-- SET ANSI_NULL_DFLT_ON to OFF and create table t3.
SET ANSI_NULL_DFLT_ON OFF
GO
CREATE TABLE t3 (a tinyint) 
GO 
-- NULL insert should fail.
INSERT INTO t3 (a) VALUES (null)
GO
-- The code from this point on demonstrates that SET ANSI_NULL_DFLT_ON 
-- has no effect when the 'ANSI null default' for the database is true.
-- Set the 'ANSI null default' database option to true.
EXEC sp_dboption 'pubs','ANSI null default','true'
GO
-- Create table t4.
CREATE TABLE t4 (a tinyint) 
GO 
-- NULL INSERT should succeed.
INSERT INTO t4 (a) VALUES (null)
GO
-- SET ANSI_NULL_DFLT_ON to ON and create table t5.
SET ANSI_NULL_DFLT_ON ON
GO
CREATE TABLE t5 (a tinyint)
GO 
-- NULL INSERT should succeed.
INSERT INTO t5 (a) VALUES (null)
GO
-- SET ANSI_NULL_DFLT_ON to OFF and create table t6.
SET ANSI_NULL_DFLT_ON OFF
GO
CREATE TABLE t6 (a tinyint)
GO 
-- NULL INSERT should succeed.
INSERT INTO t6 (a) VALUES (null)
GO
-- Set the 'ANSI null default' database option to false.
EXEC sp_dboption 'pubs','ANSI null default','false'
GO
-- Drop tables t1 through t6.
DROP TABLE t1
DROP TABLE t2
DROP TABLE t3
DROP TABLE t4
DROP TABLE t5
DROP TABLE t6
GO

请参见

ALTER TABLE

CREATE TABLE

SET

SET ANSI_DEFAULTS

SET ANSI_NULL_DFLT_OFF