I am trying to update a sql table with x amount of rows from an ordered query, where x is the balance of 100000 - a previous result. I am using ROWCOUNT to limit the number of results due to x being a parameter but don't think this works.
Can anyone suggest a fix or alternative without cursors?
DECLARE @Top int
SET @Top = 100000 - @CountRecords
SET ROWCOUNT @Top
UPDATE
UpdateTable
SET
UpdateField = 'SomeValue'
WHERE
Id IN
(
SELECT
TOP 100% Id开发者_如何学JAVA
FROM
SelectTable
WHERE
(SelectField1 IS NULL) AND
(SelectFieldDate IS NOT NULL)
ORDER BY
SelectFieldDate
)
SET ROWCOUNT 0
SET ROWCOUNT applies to intermediate results too so can be misleading
If you load a temp table, you can bypass this by separating the update into 2 steps
DECLARE @Top int
SET @Top = 100000 - @CountRecords
SET ROWCOUNT @Top
SELECT Id
INTO #foo
FROM
SelectTable
WHERE
(SelectField1 IS NULL) AND
(SelectFieldDate IS NOT NULL)
ORDER BY
SelectFieldDate
SET ROWCOUNT 0
UPDATE
UpdateTable
SET
UpdateField = 'SomeValue'
WHERE
Id IN
(
SELECT id FROM #foo
)
精彩评论