1

使用 SQL server (2012) 我有一个表 - TABLE_A 与列

(id, name, category, type, reference)

id - 是一个主键,由一个单独的表 (table_ID) 控制,该表保存主要的下一个可用 id。通常插入是从应用程序端(java)进行的,它负责在每次插入后将此 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 的值。任何人都可以提出任何建议吗?

4

1 回答 1

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演示

于 2013-09-05T21:13:06.477 回答