使用SQL server(2012) 我有一个表 - TABLE_A列
(id, name, category, type, reference)
id - 是一个主键,由一个separte表(table_ID)控制,该表保存主要的下一个可用id。通常插入是从应用程序端(java)进行的,它在每次插入后负责将此id更新为下一个id。 (通过EJB或手动等) 然而, 我想编写存储过程(从java应用程序调用)
- finds records in this table where (for example) reference = 'AAA' (passed as
parameter)
- Once multiple records found (all with same reference 'AAA', I want it to INSERT new
records with new ID's and reference = 'BBB', and other columns (name, category, type)
being same as in the found list.
我正在考虑类似于此
的查询INSERT INTO table_A
(ID
,NAME
,CATEGORY
,TYPE,
,Reference)
VALUES
(
**//current_nextID,**
(select NAME
from TABLE_A
where REFENCE in (/*query returning value 'AAA' */),
(select CATEGORY
from TABLE_A
where REFENCE in (/*query returning value 'AAA' */),
(select TYPE
from TABLE_A
where REFENCE in (/*query returning value 'AAA' */),
'BBB - NEW REFERENCE VALUE BE USED'
)
因为,我不知道我将插入多少条记录,即条件查询的结果集中有多少项
select /*field */
from TABLE_A
where REFENCE in (/*query returning value 'AAA' */),
我不知道如何在每张唱片上提出ID的价值。有人可以提出任何建议吗?
答案 0 :(得分:1)
从你的问题不清楚如何处理排序,但你可以做这样的事情
CREATE PROCEDURE copybyref(@ref VARCHAR(32)) AS
BEGIN
-- BEGIN TRANSACTION
INSERT INTO tablea (id, name, category, type, reference)
SELECT value + rnum, name, category, type, 'BBB'
FROM
(
SELECT t.*, ROW_NUMBER() OVER (ORDER BY id) rnum
FROM tablea t
WHERE reference = 'AAA'
) a CROSS JOIN
(
SELECT value
FROM sequence
WHERE table_id = 'tablea'
) s
UPDATE sequence
SET value = value + @@ROWCOUNT + 1
WHERE table_id = 'tablea'
-- COMMIT TRANSACTION
END
样本用法:
EXEC copybyref 'AAA';
这是 SQLFiddle 演示