在 SQL 中是否有一种好方法可以做到这一点? [英] Is there a good way to do this in SQL?
问题描述
我正在尝试完全在 SQL 中解决以下问题(ANSI 或 TSQL,在 Sybase ASE 12 中),而不依赖于游标或基于循环的逐行处理.
I am trying to solve the following problem entirely in SQL (ANSI or TSQL, in Sybase ASE 12), without relying on cursors or loop-based row-by-row processing.
注意:我已经创建了一个在应用程序层实现相同目标的解决方案(因此请不要回答"不要在 SQL 中执行此操作"),但作为原则问题(希望提高了性能)我想知道是否有一个高效的(例如没有游标)纯 SQL 解决方案.
设置:
我有一个表 T,其中包含以下 3 列(均为 NOT NULL):
I have a table T with the following 3 columns (all NOT NULL):
---- Table T -----------------------------
| item | tag | value |
| [int] | [varchar(10)] | [varchar(255)] |
表格在item, tag
每个标签都有一个字符串TAG##"的形式,其中##"是一个数字 1-99
Every tag has a form of a string "TAG##" where "##" is a number 1-99
不能保证现有标签是连续的,例如item 13 可能有标签TAG1"、TAG3"、TAG10".
Existing tags are not guaranteed to be contiguous, e.g. item 13 may have tags "TAG1", "TAG3", "TAG10".
TASK:我需要从另一个表 T_NEW 中插入一堆新行到表中,该表只有项目和值,并为它们分配新标签,这样它们就不会违反 item, tag
上的唯一索引.
TASK: I need to insert a bunch of new rows into the table from another table T_NEW, which only have items and values, and assign new tag to them so they don't violate unique index on item, tag
.
值的唯一性无关紧要(假设 item+value 一直是唯一的).
Uniqueness of values is irrelevant (assume that item+value is always unique already).
---- Table T_NEW --------------------------
| item | tag | value |
| [int] | STARTS AS NULL | [varchar(255)] |
问题:如何为表 T_NEW 中的所有行分配新标签,以便:
QUESTION: How can I assign new tags to all rows in table T_NEW, such that:
T 和 T_NEW 联合中的所有项目+标签组合都是唯一的
All item+tag combinations in a union of T and T_NEW are unique
新分配的标签都应采用TAG##"形式
Newly assigned tags should all be in the form "TAG##"
理想情况下,新分配的标签应该是给定项目可用的最小标签.
Newly assigned tags should ideally be the smallest available for a given item.
如果有帮助,您可以假设我已经有一个临时表 #tags
,其中有一个标签"列,其中包含 99 行,其中包含所有有效标签 (TAG1..TAG99, 每行一个)
If it helps, you can assume that I already have a temp table #tags
, with a "tag" column that contains 99 rows containing all the valid tags (TAG1..TAG99, one per row)
推荐答案
试试这个:
DECLARE @T TABLE (ITEM INT, TAG VARCHAR(10), VALUE VARCHAR(255))
INSERT INTO @T VALUES
(1,'TAG1', '100'),
(2,'TAG2', '200')
DECLARE @T_NEW TABLE (ITEM INT, TAG VARCHAR(10), VALUE VARCHAR(255))
INSERT INTO @T_NEW VALUES
(3,NULL, '500'),
(4,NULL, '600')
INSERT INTO @T
SELECT
ITEM,
('TAG' + CONVERT(VARCHAR(20),ITEM)) AS TAG,
VALUE
FROM
@T_NEW
SELECT * FROM @T
这篇关于在 SQL 中是否有一种好方法可以做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!