1、数据表
创建表语句
CREATE TABLE [dbo].[t_user] (
[USER_ID] nvarchar(32) COLLATE Chinese_PRC_CI_AS NOT NULL,
[USER_NAME] nvarchar(32) COLLATE Chinese_PRC_CI_AS NULL,
[USER_PASSWORD] nvarchar(32) COLLATE Chinese_PRC_CI_AS NULL,
[USER_EMAIL] nvarchar(32) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT [PK__t_user__F3BEEBFF7F60ED59] PRIMARY KEY CLUSTERED ([USER_ID])
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
)
ON [PRIMARY]
GO
ALTER TABLE [dbo].[t_user] SET (LOCK_ESCALATION = TABLE)
GO
CREATE NONCLUSTERED INDEX [IDX_NAME]
ON [dbo].[t_user] (
[USER_NAME] ASC
)
插入数据
INSERT INTO [dbo].[t_user]([USER_ID], [USER_NAME], [USER_PASSWORD], [USER_EMAIL]) VALUES (N'1', N'唐三', N'tangsan', N'tangsan@qq.com');
INSERT INTO [dbo].[t_user]([USER_ID], [USER_NAME], [USER_PASSWORD], [USER_EMAIL]) VALUES (N'2', N'小舞', N'xiaowu', N'xiaowu@qq.com');
INSERT INTO [dbo].[t_user]([USER_ID], [USER_NAME], [USER_PASSWORD], [USER_EMAIL]) VALUES (N'3', N'大明', N'daming', N'');
INSERT INTO [dbo].[t_user]([USER_ID], [USER_NAME], [USER_PASSWORD], [USER_EMAIL]) VALUES (N'4', N'二明', N'erming', NULL);
查看数据
1、ISNULL
使用指定的替换值替换NULL
语法:ISNULL ( expression1 , expression2 )
注释:如果 expression1不为NULL,则返回expression1的值;否则返回expression2的值。
示例
SELECT
USER_ID,
USER_NAME,
USER_PASSWORD,
ISNULL(USER_EMAIL,'这个值为NULL') AS USER_EMAIL
FROM
t_user
结果
2、NULLIF
判断两个值是否相等,相等返回NULL,不相等返回第一个值
语法:ISNULL ( expression1 , expression2 )
注释:如果expression1和expression2相等则返回NULL;否则返回expression1
示例
SELECT
USER_ID,
-- 跟唐四比较,不相等则返回前者
NULLIF(USER_NAME, '唐四') AS USER_NAME_1,
-- 跟唐三比较,相等则返回NULL
NULLIF(USER_NAME, '唐三') AS USER_NAME_2,
USER_PASSWORD,
USER_EMAIL
FROM
t_user
结果
3、ISNULL与NULLIF的联合使用
把查出唐三改名为唐四
SELECT
USER_ID,
USER_NAME,
-- 使用NULLIF跟唐三比较,相等则返回NULL;再判断是否为NULL,是则返回唐四
ISNULL(NULLIF(USER_NAME, '唐三'),'唐四') AS USER_NAME_1,
USER_PASSWORD,
USER_EMAIL
FROM
t_user
结果