I am working on a query which I am updating a user defined table that always has 1 row (it's part of a much larger operation). This table is populated by querying from a larger employee table based on employee ID.
This query is working most of the time but in some scenarios I am getting a
'Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.'
error.
UPDATE @empInfo SET lastpromotiondate = ISNULL((
SELECT begindate
FROM performanceyear
WHERE lastpromotiondate BETWEEN
begindate AND enddate AND performanceyear.[fk_function_id] =
functionid AND isfederal =
performanceyear.federal), lastpromotiondate)
I couldn't pinpoint exactly why, I tried populating the values using a select and it was only returning 1 result.
I was at a loss, so I tried below and it worked.
UPDATE @empInfo SET LastPromotionDate = ISNULL((
SELECT begindate
FROM performanceyear
WHERE (SELECT LastPromotionDate FROM @empinfo) BETWEEN begindate AND enddate
AND [FK_Function_ID] = (SELECT FunctionID FROM @empinfo)
AND Federal = (SELECT isFederal FROM @empinfo)
), LastPromotionDate)
They definitely don't execute the same at all but I feel like I am missing something here. Why does one work and not the other? @empInfo only has 1 row.
Edit2:
I seem to have thought myself into a corner on this one!
The ORIGINAL query which was returning the error was:
UPDATE @empInfo SET LastPromotionDate =
ISNULL((
SELECT begindate
FROM performanceyear
WHERE LastPromotionDate BETWEEN begindate AND enddate
AND performanceyear.[FK_Function_ID] = FunctionID
AND Federal = performanceyear.Federal)
,LastPromotionDate)
@empInfo had a 'Federal' column and so did 'performanceyear' when I looked into the execution plan of this one, it was comparing 'performanceyear'.Federal to 'performanceyear'.Federal. So I changed the @empInfo Federal name it isFederal and it worked.
The reason my other test was causing an issue was not because of 2 rows in @empinfo. It was because I was running update and then update again. The first update caused the second one to return 2 results from performanceyear.
Run independently they work.
With that all said, I still don't know of a solution which would work without the columns being different names since I can't use an alias on @empInfo in the update subquery.