SQL增量id插入没有自动键

时间:2015-09-03 05:48:17

标签: sql sql-server sql-server-2008

我正在尝试执行以下查询作为处理多个记录的简单方法,而不是为每个记录创建一个insert语句:

INSERT INTO wostatus (WO, STATUS, DATE, WOSTATUSID)
   SELECT  
       workorder.wonum, 'CLOSE', '02-SEP-2015', 
       (SELECT MAX(wostatusid) + 1 FROM wostatus)
   FROM  
       wostatus 
   JOIN
       workorder ON wostatus.wonum = workorder.wonum

但是我遇到了重复的密钥错误,所以这不能递归地工作。我认为它将继续插入+1并检索下一个插入的新值。还有另一种简单的方法可以在SS和Oracle上运行吗?

5 个答案:

答案 0 :(得分:0)

使用以下查询

INSERT INTO wostatus (WO,STATUS,DATE,WOSTATUSID)
SELECT workorder.wonum, 'CLOSE', '02-SEP-2015', ((SELECT isnull(max(wostatusid),0) from wostatus)+ row_number() over(order by wostatus.wonum))
from wostatus join workorder on wostatus.wonum = workorder.wonum

答案 1 :(得分:0)

您可以使用ROW_NUMBER

INSERT INTO wostatus (WO,STATUS,DATE,WOSTATUSID)
SELECT 
    workorder.wonum, 
    'CLOSE', 
    '02-SEP-2015', 
    (SELECT max(wostatusid)+1 from wostatus) + ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) - 1
FROM wostatus 
JOIN workorder 
    ON wostatus.wonum = workorder.wonum

答案 2 :(得分:0)

在TSQL中你可以写成:

DECLARE @maxwostatusid INT;
SELECT @maxwostatusid = max(wostatusid) from wostatus;

INSERT INTO wostatus (WO,STATUS,DATE,WOSTATUSID)
SELECT WO.wonum, 'CLOSE', '02-SEP-2015',
@maxwostatusid + ROW_NUMBER() OVER(ORDER BY WO.wonum ASC)
from wostatus WS
join workorder WO on WS.wonum = WO.wonum

答案 3 :(得分:0)

以下内容适用于SQL Server 2008。

不确定Oracle是否有类似的ROW_NUMBER()

DECLARE @MaxWoStatusId INT;

SELECT @MaxWoStatusId = MAX(wostatusid) + 1 from wostatus;

INSERT INTO wostatus (WO,STATUS,DATE,WOSTATUSID)
SELECT workorder.wonum, 'CLOSE', '02-SEP-2015', ROW_NUMBER() OVER(ORDER BY workorder.wonum) + @MaxWoStatusId
FROM workorder

答案 4 :(得分:-1)

Declare @sql nvarchar(max);

Declare @maxv varchar(10)= (SELECT max(wostatusid)+1 from wostatus);

set @sql='INSERT INTO wostatus (WO,STATUS,DATE,WOSTATUSID)
SELECT workorder.wonum, ''CLOSE'', ''02-SEP-2015'', (SELECT '+ @maxv+'+row_number() over (order by wostatusid) from wostatus group by wostatusid)
from wostatus join workorder on wostatus.wonum = workorder.wonum '
exec (@sql);