我想在我的SQL脚本中包含一个If语句

时间:2015-12-30 21:58:39

标签: sql sql-server tsql if-statement sql-server-2012

我有这个我写的插入语句,但我想在将数据插入数据库之前测试null>以下是代码

use master
DECLARE @PriviledgeID uniqueidentifier
DECLARE @UserName uniqueidentifier 

SELECT @PriviledgeID=roleId 
FROM aspnet_Roles 
WHERE RoleName = 'Operator'

SELECT @UserName=USERID
FROM aspnet_Users
WHERE username = ments@point.com'


INSERT INTO aspnet_UsersInRoles
 VALUES(@UserName, @PriviledgeID )

我的目标是确保我不在数据库中插入null值,我该怎么做?感谢。

2 个答案:

答案 0 :(得分:1)

首先添加此检查:

IF (@UserName IS NOT NULL AND @PriviledgeID IS NOT NULL)
   INSERT INTO aspnet_UsersInRoles
   VALUES(@UserName, @PriviledgeID )

答案 1 :(得分:0)

INSERT INTO aspnet_UsersInRoles
SELECT roleId, USERID 
  FROM aspnet_Roles  
 cross join aspnet_Users
 where RoleName = 'Operator'
   and username = 'ments@point.com' 
   and roleId is not null 
   and USERID is not null