开发者

SQL Server 2000 Update based on nested SELECT with TOP

开发者 https://www.devze.com 2023-02-08 22:35 出处:网络
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

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
    )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号