UPDATE
dbo.FormDetail
SET
FieldOrder=FieldOrder+1
WHERE
WHERE DocCode IN (1,2,3)
AND FieldOrder >= (SELECT FieldOrder FROM dbo.FormDetail
WHERE FieldData LIKE '%OldField%'
AND DocCode IN (1,2,3))
Don’t know how clear it is what I’m trying to do here but I want to increase the FieldOrder in the FormDetail table for a number of documents but only after a certain field (basically so I have a gap to insert a new field). But the obvious problem is that the FieldOrder I get in my Where will not be specific to the document that the statement may currently be updating. I was thinking it’s probably possible using partitions but I have only ever used partitions in From sections. Any help would be really appreciated.
UPDATE
dbo.FormDetail Sample Data
DocCode FieldOrder FieldData
1 1 ‘Title’
1 2 ‘OldField’
1 3 ‘Signature’
2 1 ‘Paragraph’
2 2 ‘OldField’
3 1 ‘OldField’
In your existing code your sub-query is executed once and returns all it’s results in one go to your outer query.
What you actually appear to want is for the sub-query to be executed once for every row being processed by the outer query. The is called a correlated sub-query.
To make it work like that I have made two changes;
1. I’ve given the table an alias in the sub-query
2. I’ve changed the sub-query WHERE clause to reference the table in the outer-query
Another alternative could be to join on a sub-query…