TSQL:我如何检测和插入丢失的记录

TSQL: How do i detect and insert missing records(TSQL:我如何检测和插入丢失的记录)
本文介绍了TSQL:我如何检测和插入丢失的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的 T-SQL 表.

I have T-SQL Table below.

 ID   Cost    MaxCost
 -------------------------------
 2    200     300
 3    400     1000
 6    20      100

上表必须有 10 行 ID 为 1 到 10.所以它缺少 7 行.如何插入具有正确 ID 的缺失行.成本&缺失行的 maxcost 将为零.我是否需要创建一个包含 1 到 10 个数字的临时表?

The above table must have 10 rows with IDs 1 to 10. So its missing 7 rows. How do i insert missing rows with proper ID. The cost & maxcost for missing rows will be zero. Do i need to create a temp table that holds 1 to 10 numbers?

推荐答案

不需要临时表,简单的tally派生表和LEFT OUTER JOIN就足够了:

No need for temp table, simple tally derived table and LEFT OUTER JOIN are sufficient:

CREATE TABLE #tab(ID INT, Cost INT, MaxCost INT);

INSERT INTO #tab(ID, Cost, MaxCost)
VALUES (2, 200,300),(3, 400, 1000) ,(6, 20, 100);

DECLARE @range_start INT = 1
       ,@range_end INT = 10;

;WITH tally AS
(
  SELECT TOP 1000 r = ROW_NUMBER() OVER (ORDER BY name)
  FROM master..spt_values
)
INSERT INTO #tab(id, Cost, MaxCost)
SELECT t.r, 0, 0
FROM tally t
LEFT JOIN #tab c
  ON t.r = c.ID
WHERE t.r BETWEEN @range_start AND @range_end
  AND c.ID IS NULL;

SELECT *
FROM #tab
ORDER BY ID;

LiveDemo

Tally 表只是数字表.有很多方法可以使用 子查询:

Tally table is simply number table. There are many ways to achieve it with subquery:

  • 递归 cte
  • ROW_NUMBER() 来自包含许多值的系统表(此处使用)
  • UNION ALLCROSS JOIN
  • VALUES(...)
  • 使用 OPENJSON (SQL Server 2016+)
  • ...
  • recursive cte
  • ROW_NUMBER() from system table that holds many values (used here)
  • UNION ALL and CROSS JOIN
  • VALUES(...)
  • using OPENJSON (SQL Server 2016+)
  • ...

TOP 1000 将仅生成 1000 条记录,如果您知道需要更多记录可以使用:

The TOP 1000 will generate only 1000 records if you know that you need more you can use:

SELECT TOP 1000000 r = ROW_NUMBER() OVER (ORDER BY (SELECT 1))
FROM master..spt_values c
CROSS JOIN master..spt_values c2;

这篇关于TSQL:我如何检测和插入丢失的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)