How to use OFFSET and Fetch without Order by in SQL Server(如何在 SQL Server 中使用 OFFSET 和 Fetch without Order by)
问题描述
我想在我的 SQL Server 2012 查询中使用 OFFSET 和 Fetch.但没有任何 order by.我不能使用 order by.因为我的排序顺序会丢失.如何在没有 order by 和行号以及查询中的位置的情况下使用 OFFSET 和 Fetch?我的 2 个选择表具有相同的结构.
I want use OFFSET and Fetch in my SQL server 2012 query.But without any order by.I can not use order by.Because my sort order will be lost. How can I use OFFSET and Fetch without order by and row number and where in my query? My 2 select tables have same structure.
INSERT INTO @TempTable [some columns]
select [some columns] from table1 order by col1
INSERT INTO @TempTable [same columns]
select [some columns] from table2 order by col2
select * from @TempTable OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY
此查询在 OFFSET 关键字处有语法错误.
This query has syntax error at OFFSET keyword.
推荐答案
通过向临时表变量添加标识列
By adding an identity column to the temp table variable
declare @TempTable table([some columns], rownr int identity(1,1) )
INSERT INTO @TempTable [some columns]
select [some columns] from table1 order by col1
INSERT INTO @TempTable [same columns]
select [some columns] from table2 order by col2
为每行添加一个自动递增编号,按照它们添加到临时表的顺序.插入内容不需要填充此列,因此插入内容可以保持原样.然后可以将标识列用于订单:
An automatic incrementing number is added for each row, in the order in which they are added to the temp table. The inserts don't need to fill this column, so the inserts can remain as they are. The identity column can then be used for the order by:
select * from @TempTable Order by rownr OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY
这篇关于如何在 SQL Server 中使用 OFFSET 和 Fetch without Order by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQL Server 中使用 OFFSET 和 Fetch without Order by
基础教程推荐
- 是否可以执行按位分组功能? 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
