SQL Join only on condition?
I have开发者_运维问答 about 10 different sql statements that update different tables. They look similar to this:
Update Y
SET x = n
Where something = @somevar
Now I need to Update only certain rows when the @hasRows var is set. I could simply do this:
if not @hasRows is null
begin
Update Y
SET x = n
from Y inner join #items on y.Item = #items.Item
Where something = @somevar
end
else
begin
Update Y
SET x = n
Where something = @somevar
end
Is there a way to avoid the if/else and do the update in one statement?
I am using SQL2005.
Perhaps something like this: (copypasta your example)
UPDATE Y
SET x = n
FROM Y
WHERE something = @somevar
AND (
(@Items IS NULL)
OR (y.Item = @Item)
)
The JOIN
isn't used but it's always proceeding if @items
is NULL
, or using the intended condition.
Problem here is that your example seems to include a TVP @ITEMS
but TVPs don't exist in SQLServer2k5? So whatever the value is should be placed in the parameter.
Alternatively, if #Table exists but has no rows you can do this:
UPDATE Y
SET x = n
FROM Y
JOIN #Items ON (@HasRows = 0) OR (#Items.Item = Y.Item)
WHERE something = @somevar
If you don't know whether or not #Items IS NULL
then your condition is your option because declared variables are resolved before the statement is executed.
精彩评论