简体   繁体   English

C#SQL如何选择和处理N条记录,然后对其进行更新?

[英]C# SQL How to select and process N records, and then update them?

I retrieve some records by running this query: 我通过运行此查询来检索一些记录:

SELECT * FROM [MyTable] order by [Date] OFFSET N ROWS FETCH NEXT 500 ROWS ONLY

Where N is a number that starts from 0 and increment by 500. There are multiple instances of this application and each instance gets 500 records. 其中N是一个从0开始并递增500的数字。此应用程序有多个实例,每个实例获取500条记录。

Now the question is, how do I update the retrieved records? 现在的问题是,如何更新检索到的记录? The records don't have primary key. 记录没有主键。 I tried something like this but the syntax isn't right: 我尝试了类似的方法,但是语法不正确:

UPDATE [MyTable] SET [status] = 1 order by [Date] OFFSET N ROWS FETCH NEXT 500 ROWS

Note: I can't use WHERE status = 0 because I want one instance to only deal with the records it retrieved. 注意:我不能使用WHERE status = 0,因为我希望一个实例仅处理它检索到的记录。

Any idea? 任何想法?

You could try something like this: 您可以尝试这样的事情:

UPDATE x
 SET [status] = 1
FROM (
      SELECT * FROM [MyTable] order by [Date] OFFSET N ROWS FETCH NEXT 500 ROWS ONLY
      ) x
UPDATE x
SET x.[status] = 1
OUTPUT deleted.*
FROM
    (
        SELECT * 
        FROM [MyTable] 
        WHERE 
            [status] = 0 
        ORDER BY [Date] 
        OFFSET N ROWS FETCH NEXT 500 ROWS ONLY
    ) x;

Be careful though, your "fetch next" is preventing any rows from being returned if there are not at least 500 to return. 但是请小心,如果没有至少500行要返回,则“下一步获取”将阻止返回任何行。 Maybe that's what you want. 也许这就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 Select 不同的记录然后在 C# Access 数据库中统计它们? - How to Select Distinct records then count them in C# Access database? 选择一些记录,然后在asp.net c#中同时更新它们 - select some records and then update them simultaneuosly in asp.net c# 我需要使用 large.CSV 文件创建一个新的 ETL C# 进程到 SQL 表添加/更新记录 - I need to create a new ETL C# process with large .CSV files to SQL Tables Add/Update records 在 c# 和 sql 中更新循环性能中的记录 - Update records in a loop performance in c# and sql 从SQLite C#中选择N条随机记录 - Select N Random Records from SQLite C# 使用视图在C#中进行数据绑定以及如何更新它们 - Databinding in C# with views and how to update them 在表中保存记录后,如何循环遍历具有相同 ID 的所有记录并在 ASP.NET MVC C# 中更新它们 - After saving a record in a table, how to loop through all records with same ID and update them in ASP.NET MVC C# 使用C#如何从SQL数据库中有效检索和更新数千条记录 - Using c# how to retrieve and update thousands of records from a SQL database efficiently 如何在C#ASP.NET MVC项目中使用ajax更新SQL表中的记录顺序? - How to update orders of records in SQL table using ajax in C# ASP.NET MVC project? Select C# 中 SQL 服务器的带换行符(“\n”)的记录 - Select record with newline character ("\n") from SQL Server in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM