我有一个来源,我从中提取数据以更新现有表。
是否只有在源数据不是时才更新每个字段中的值NULL
?
你应该使用ISNULL(@paramA, ColumnA)
:
UPDATE someTable
set ColumnA = ISNULL(@ParamA, ColumnA)
WHERE
.....
考虑到你提到如果源数据不为空然后更新
--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