在sql server中更新null值

时间:2013-06-12 06:46:20

标签: sql sql-server

如果用户没有选择值,或者在用户选择值时设置新值,如何将列值设置为null

create procedure update2
 @SSN int,
 @Employee_FirstName varchar(50),
 @Employee_lastName varchar(50),
 @gender_ID int,
 @Department_ID int,
 @location_ID int,
 @salary decimal(18, 3)

as

Update Employee set Employee_FirstName= @Employee_FirstName,
Employee_lastName=@Employee_lastName,gender=@gender_ID,Department_ID = @Department_ID,
location_ID=@location_ID or location_ID is null  , salary=@salary
where SSN = @SSN

3 个答案:

答案 0 :(得分:0)

您可以将@location_ID声明为null

CREATE PROCEDURE update2
@SSN INT ,
@Employee_FirstName VARCHAR(50) ,
@Employee_lastName VARCHAR(50) ,
@gender_ID INT ,
@Department_ID INT ,
@location_ID INT = NULL ,
@salary DECIMAL(18, 3)

AS 

UPDATE  Employee
SET     Employee_FirstName = @Employee_FirstName ,
        Employee_lastName = @Employee_lastName ,
        gender = @gender_ID ,
        Department_ID = @Department_ID ,
        location_ID = @location_ID ,
        salary = @salary
WHERE   SSN = @SSN

答案 1 :(得分:0)

试试这个,如果我正确理解你的问题 -

CREATE PROCEDURE dbo.update2 

    @SSN INT,
    @Employee_FirstName VARCHAR(50),
    @Employee_lastName VARCHAR(50),
    @gender_ID INT,
    @Department_ID INT,
    @location_ID INT,
    @salary DECIMAL(18, 3)

AS BEGIN

    UPDATE dbo.Employee
    SET 
          Employee_FirstName = @Employee_FirstName
        , Employee_lastName = @Employee_lastName
        , gender = @gender_ID
        , Department_ID = @Department_ID
        , location_ID = ISNULL(location_ID, @location_ID) --<-- ?? 
        , salary = @salary
    WHERE SSN = @SSN

END 

答案 2 :(得分:0)

@location_ID INT = NULL - 在任何需要的地方指定NULL

但是您必须删除此特定列的任何关系(外键)否则您将在更新时发生冲突错误

由于 阿伦安东尼