在插入查询中插入序列号使用选择查询

时间:2012-02-21 11:58:18

标签: sql sql-server-2008 tsql

我想在两个数据库之间复制一些数据,因此我使用如下的Insert查询:

INSERT INTO [NewDB].[MyTable]
(
[FirstName],
[LastName],
[Number]
)
(
SELECT [ST].[FirstName], [ST].[LastName], **SequentialNumber**
FROM [SourceDB].[SourceTable] AS [ST]
);
GO

但是新表有一个名为Number的新的唯一int非空列,所以如何使用以下脚本插入序列号(实际上是10位数),有些东西如1234567891,1234567892,...... ,有人有任何想法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER()功能,例如:

INSERT INTO [NewDB].[MyTable]
(
    [FirstName],
    [LastName],
    [Number]
)

SELECT [ST].[FirstName], [ST].[LastName], ROW_NUMBER() OVER(ORDER BY [ST].[FirstName])
FROM [SourceDB].[SourceTable] AS [ST]

答案 1 :(得分:0)

也许是这样的:

;WITH CTE AS
(
    SELECT 
        [ST].[FirstName], 
        [ST].[LastName], 
        ROW_NUMBER() OVER(ORDER BY [ST].[FirstName]) AS rowNbr
    FROM 
        [SourceDB].[SourceTable] AS [ST]
)
INSERT INTO [NewDB].[MyTable]
(
    [FirstName],
    [LastName],
    [Number]
)
SELECT
    CTE.[FirstName],
    CTE.[LastName]
    1234567890+(CTE.rowNbr-1)
FROM
    CTE

答案 2 :(得分:0)

你可以这样做:

INSERT INTO [MyTable]
(
[FirstName],
[LastName],
[Number]
)

SELECT [ST].[FirstName], [ST].[LastName], (select max(number)+1 from [MyTable])
FROM [SourceTable] AS [ST]

如果您在MyTable上没有记录,则需要在select上处理NULL值的案例