许多INSERT的单个SQL语句

时间:2015-08-03 15:02:10

标签: sql sql-server

请参阅下面的DDL:

CREATE TABLE #Test (ID INT NOT NULL IDENTITY, Name varchar(100), [Key] int, primary key (ID))
INSERT INTO #Test (Name, [Key]) values ('Ian',1)
INSERT INTO #Test (Name, [Key]) values ('Iain',1)
INSERT INTO #Test (Name, [Key]) values ('Eon',1)
INSERT INTO #Test (Name, [Key]) values ('Mark',2)
INSERT INTO #Test (Name, [Key]) values ('Steven',2)

和下面的DDL:

CREATE TABLE #Test2 (ID INT NOT NULL IDENTITY, Name varchar(100), primary key (ID))
INSERT INTO #Test2 (Name) values ('Graham')
INSERT INTO #Test2 (Name) values ('William')
INSERT INTO #Test2 (Name) values ('Neil')
INSERT INTO #Test2 (Name) values ('Calum')
INSERT INTO #Test2 (Name) values ('Wayne')

我想将#Test2中的所有内容插入到#Test中。我希望#Test2中的每条记录在#Test中都有一个唯一的密钥。实际上,我希望这种情况发生:

INSERT INTO #Test (Name, [Key]) VALUES ('Graham', 3)
INSERT INTO #Test (Name, [Key]) VALUES ('William', 4)
INSERT INTO #Test (Name, [Key]) VALUES ('Calum', 5)
INSERT INTO #Test (Name, [Key]) VALUES ('Wayne', 6)

#Test和#Test2中有数百万条记录。

是否可以使用单个SQL语句执行所有INSERTS,或者是否必须使用游标。

2 个答案:

答案 0 :(得分:3)

您只需要高于最大值的新数字。存在的关键?这应该有效:

declare @maxkey int
select @maxkey = max([Key]) from Test

insert into Test (Name, [Key]) 
select Name, row_number () over (order by (select null)) + @maxkey
from Test2

这只是获取最大值。键并使用row_number将数字添加到来自Test2的行。

SQL Fiddle

答案 1 :(得分:0)

您可以尝试这样的逻辑:

Sub test()
Dim lastRow1 As Integer, lastRow2 As Integer, newLastRow As Integer, lastCol As Integer, i As Integer
Dim headers() As Variant
Dim cel As Range

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

ReDim headers(2)

headers() = Array("Name", "Class", "Marks")


lastRow1 = Cells(1, 1).End(xlDown).Row
lastRow2 = Cells(1, 4).End(xlDown).Row

Dim rng1 As Range, rng2 As Range
Set rng1 = Range(Cells(2, 1), Cells(lastRow1, 3))
Set rng2 = Range(Cells(2, 4), Cells(lastRow2, 6))

'Search List2's name column to delete any duplicate names that are in Col A.
For i = 2 To lastRow2
    If WorksheetFunction.CountIf(Range(Cells(2, 1), Cells(lastRow1, 1)), Cells(i, 4).Value) > 0 Then
        Debug.Print "Delete"
        Range(Cells(i, 4), Cells(i, 7)).Delete shift:=xlUp
        i = i - 1
    End If
Next i

Range(Cells(1, 7), Cells(1, 9)) = headers()

lastRow2 = Cells(1, 4).End(xlDown).Row
newLastRow = 2
rng1.Copy Range(Cells(newLastRow, 7), Cells(newLastRow, 7))
newLastRow = Cells(2, 7).End(xlDown).Row + 1

Set rng2 = Range(Cells(2, 4), Cells(lastRow2, 6))
rng2.Copy Range(Cells(newLastRow, 7), Cells(newLastRow, 7))

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

这是我的小提琴示例:Fiddle