如果已包含数据,则不允许空值更新列

时间:2013-10-10 21:36:30

标签: sql

我有一个来源,我从中提取数据以更新现有表。

仅当源数据不是NULL时,才能更新每个字段中的值吗?

2 个答案:

答案 0 :(得分:4)

您应该使用ISNULL(@paramA, ColumnA)

UPDATE someTable
set ColumnA = ISNULL(@ParamA, ColumnA)
WHERE
.....

答案 1 :(得分:-1)

考虑到你提到的源数据不是null然后更新

--Create a sample table

DECLARE @SAMPLE TABLE
(
SourceID INT IDENTITY(1,1),
SourceData NVARCHAR(255)
)

--Create dummy data

INSERT INTO @SAMPLE VALUES ('SOMETHING')
INSERT INTO @SAMPLE VALUES (NULL)
INSERT INTO @SAMPLE VALUES ('SOMETHING')


--update source data that is not null, this will update entire table

UPDATE @SAMPLE
SET SourceData = 'New Data'
FROM @SAMPLE t1
INNER JOIN (
SELECT * FROM @SAMPLE Where SourceData is not null) t2 
ON t1.SourceID = t2.SourceID

或者如果您只想更新所选记录

--Pass in your variable

DECLARE @SourceID INT

--play around your source id

SET @SourceID = 2

--if the particular id is with null data, then update will never perform

IF EXISTS(SELECT 1 FROM @SAMPLE WHERE SourceID = @SourceID and SourceData is not null)
Update @SAMPLE
set SourceData = 'New Item'
where SourceID = @SourceID