当数据库的 ANSI null default 选项是 true 时,更改会话行为以替代新列的默认为空性。有关设置 ANSI null default 值的更多信息,请参见 sp_dboption 和设置数据库选项。
SET ANSI_NULL_DFLT_OFF {ON | OFF}
当在 CREATE TABLE 和 ALTER TABLE 语句中没有指定列的为空性时,该设置仅影响新列的为空性。当 SET ANSI_NULL_DFLT_OFF 为 ON 时,如果没有显式指定列的为空性状态,默认情况下,使用 ALTER TABLE 和 CREATE TABLE 语句创建的新列将为 NOT NULL。SET ANSI_NULL_DFLT_OFF 对使用显式 NULL 或 NOT NULL 创建的列无效。
不能将 SET ANSI_NULL_DFLT_OFF 和 SET ANSI_NULL_DFLT_ON 同时设置为 ON。如果将一个选项设置为 ON,则将另一个选项设置为 OFF。因此,可以或者将 ANSI_NULL_DFLT_OFF 或 SET 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。
SET ANSI_NULL_DFLT_OFF 的设置是在执行或运行时设置,而不是在分析时设置。
SET ANSI_NULL_DFLT_OFF 权限默认授予所有用户。
下例显示 SET ANSI_NULL_DFLT_OFF 使用 ANSI null default 数据库选项的两个设置时的效果。
USE pubs
GO
-- Set the 'ANSI null default' database option to true by executing
-- sp_dboption.
GO
EXEC sp_dboption 'pubs','ANSI null default','true'
GO
-- Create table t1.
CREATE TABLE t1 (a tinyint)
GO
-- NULL INSERT should succeed.
INSERT INTO t1 (a) VALUES (null)
GO
-- SET ANSI_NULL_DFLT_OFF to ON and create table t2.
SET ANSI_NULL_DFLT_OFF ON
GO
CREATE TABLE t2 (a tinyint)
GO
-- NULL INSERT should fail.
INSERT INTO t2 (a) VALUES (null)
GO
-- SET ANSI_NULL_DFLT_OFF to OFF and create table t3.
SET ANSI_NULL_DFLT_OFF off
GO
CREATE TABLE t3 (a tinyint)
GO
-- NULL INSERT should succeed.
INSERT INTO t3 (a) VALUES (null)
GO
-- This illustrates the effect of having both the sp_dboption and SET
-- option disabled.
-- Set the 'ANSI null default' database option to false.
EXEC sp_dboption 'pubs','ANSI null default','false'
GO
-- Create table t4.
CREATE TABLE t4 (a tinyint)
GO
-- NULL INSERT should fail.
INSERT INTO t4 (a) VALUES (null)
GO
-- SET ANSI_NULL_DFLT_OFF to ON and create table t5.
SET ANSI_NULL_DFLT_OFF ON
GO
CREATE TABLE t5 (a tinyint)
GO
-- NULL insert should fail.
INSERT INTO t5 (a) VALUES (null)
GO
-- SET ANSI_NULL_DFLT_OFF to OFF and create table t6.
SET ANSI_NULL_DFLT_OFF OFF
GO
CREATE TABLE t6 (a tinyint)
GO
-- NULL insert should fail.
INSERT INTO t6 (a) VALUES (null)
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
相关文章