I'm trying an update with a conditional sub-select which could return null...
UPDATE
aTable SET
aColumn =
(
SELECT TOP 1
CASE
WHEN bTable.someColumn = 1 THEN someValue1
WHEN bTable.someColumn = 2 THEN someValue2
ELSE someValue3
END
FROM
bTable
WHERE
bTable = @someCriteria
ORDER BY
someSortColumn
) WHERE
aTable.id = @someId;
If the "bTable = @someCriteria" clause causes no results to be returned from the SELECT, it attempts to insert a NULL into "aColumn", which in this case is a NOT NULL column.
Question
How do I get it to simply leave "aColumn" alone in this circumstance?
Many thanks.
UPDATE [table] SET [column]=0 WHERE [column] IS NULL; Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0.
For a scalar subquery: If the subquery returns no rows, the result of the scalar subquery is NULL . If the subquery returns more than one row, it is an error. If the subquery returns one row, the result is the value of the query's (only) column for that row.
...
aColumn =
ISNULL(
(
SELECT TOP 1
CASE
WHEN bTable.someColumn = 1 THEN someValue1
WHEN bTable.someColumn = 2 THEN someValue2
ELSE someValue3
END
FROM
bTable
WHERE
bTable = @someCriteria
ORDER BY
someSortColumn
), aColumn)
...
UPDATE A SET
aColumn = B.Value
FROM aTable AS A
CROSS JOIN
(
SELECT TOP 1
CASE
WHEN bTable.someColumn = 1 THEN someValue1
WHEN bTable.someColumn = 2 THEN someValue2
ELSE someValue3
END
FROM
bTable
WHERE
bTable = @someCriteria
ORDER BY
someSortColumn
) AS B(Value)
WHERE
A.id = @someId;
Difference between my answer and answer by gbn is that here column aColumn
is not modified. I think that the isnull(..., aColumn)
actually updates the value so if you have an update trigger it will fire.
UPDATE aTable
SET aColumn = s.Value
FROM (
SELECT TOP 1
CASE
WHEN bTable.someColumn = 1 THEN someValue1
WHEN bTable.someColumn = 2 THEN someValue2
ELSE someValue3
END AS Value
FROM
bTable
WHERE
bTable = @someCriteria
ORDER BY
someSortColumn
) s
WHERE aTable.id = @someId
AND s.Value IS NOT NULL;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With