由于 varchar,这有点难看,但您可以尝试:
;WITH x AS
(
SELECT ROW_NUMBER() OVER(ORDER BY OrigColA, OrigColB) AS n, OrigColA, OrigColB
FROM myTableB
)
INSERT INTO myTable(KeyId, ColumnA, ColumnB)
SELECT (SELECT CAST(CAST(MAX(KeyId) AS INT) + n AS NVARCHAR(10)) FROM myTable),
OrigColA, OrigColB
FROM x;
这当然假设已经有一行myTable
可以从中获取当前最大值。
SQL 小提琴示例
如果情况并非总是如此,请MAX(KeyId)
使用 aCOALESCE
和比您的起始默认值小一的常数进行包装。例如:
;WITH x AS
(
SELECT ROW_NUMBER() OVER(ORDER BY OrigColA, OrigColB) AS n, OrigColA, OrigColB
FROM myTableB
)
INSERT INTO myTable(KeyId, ColumnA, ColumnB)
SELECT (SELECT CAST(CAST(COALESCE(MAX(KeyId),1000) AS INT) + n AS NVARCHAR(10)) FROM myTable),
OrigColA, OrigColB
FROM x;
或者,如果您知道没有一行,而您只想从一个常量开始,只需执行以下操作:
INSERT INTO myTable(KeyId, ColumnA, ColumnB)
SELECT ROW_NUMBER() OVER(ORDER BY OrigColA, OrigColB) + 1000, OrigColA, OrigColB
FROM myTableB