2008-11-25 4 views
47

J'ai un tas de lignes dans Excel que je veux coller dans une nouvelle table dans MS SQL. Y a-t-il un moyen simple?Coller des données MS Excel à SQL Server

+0

cela ne semble pas être liés à la programmation - vous essayez de le faire avec VBA ou quelque chose? – warren

+0

Non, juste de grandes quantités de données arrivant ad hoc comme Excel ou facilement, «excellent» – Bajji

+0

Ce http://dotnetstories.wordpress.com/2008/05/24/copy-paste-data-from-excel-to-sql- server-2005/a travaillé pour moi –

Répondre

29

Je l'ai utilisé cette technique avec succès dans le passé:

Using Excel to generate Inserts for SQL Server

(...) Passer une colonne (ou l'utiliser pour les notes), puis tapez quelque chose comme le suivant formule en elle:

="insert into tblyourtablename (yourkeyID_pk, intmine, strval) values ("&A4&", "&B4&", N'"&C4&"')"

maintenant que vous avez votre déclaration d'insertion pour une table avec votre clé primaire (PK), un entier et une chaîne unicode. (...)

+1

La réponse de bzlm est plus appropriée pour la question. C'est une petite découverte soignée mais dans la plupart des cas, bzlm fait un clic droit et copie des œuvres passées! – ThinkCode

+0

Ceci est plus rapide et plus simple: http://www.mssqltips.com/sqlservertip/1430/import-excel-data-into-sql-server-using-copy-and-paste/ –

+0

Copier et coller n'a pas fonctionné pour moi, ni la commande 'OPENROWSET'. Le seul moyen était la réponse de Galwegian! –

2

La façon la plus simple est de créer une colonne calculée XLS qui générerait la syntaxe de l'instruction d'insertion. Puis copiez ces insert dans un fichier texte, puis exécutez sur le SQL. Les autres alternatives sont d'acheter des add-ons de connectivité de base de données pour Excel et d'écrire du code VBA pour accomplir la même chose.

0

Si l'interface fonctionne comme il l'a fait hier je l'ai utilisé, vous pouvez sélectionner la région dans Excel, copier, ouvrez SQL Server et coller les données dans la table comme vous le feriez avec Access. Ou vous pouvez configurer un lien ODBC entre Excel et SQL Server.

1

Je pense que certains datbases peuvent importer des données à partir de fichiers CSV (valeurs séparées par des virgules), wich vous pouvez exporter exel. Ou du moins, il est assez facile d'utiliser un analyseur csv (trouvez-en un pour votre langue, n'essayez pas d'en créer un vous-même - c'est plus difficile qu'il n'y paraît) pour l'importer dans la base de données.

Je ne suis pas familier avec MS SQL, mais il ne me surprendront si elle ne supporte directement.

En tout cas, je pense que le requrement doit être que la structure de la feuille de Exel et la table de base de données est similaire.

-1

pourquoi ne pas simplement utiliser l'assistant d'export/import dans SSMS?

50

Si vous avez SQL Server Management Studio, vous pouvez simplement copier et coller à partir d'Excel dans la table dans Management Studio, en utilisant votre souris. Just

  1. Accédez à la table dans laquelle vous souhaitez coller.
  2. Sélectionnez "Modifier les 200 premières lignes".
  3. Cliquez avec le bouton droit n'importe où et sélectionnez Coller.

Avant cela, vous devez faire correspondre les colonnes entre Excel et Management Studio. En outre, vous devez placer toutes les colonnes non modifiables dernier (à droite) en utilisant le Concepteur de tables dans Management Studio.

L'ensemble de la procédure prend quelques secondes (à mise en place et démarrer - pas nécessairement à exécuter) et ne nécessite aucune instruction SQL.Vous ne pouvez pas utiliser le code VBA pour faire la copie d'Excel et coller dans les opérations SSMS?

+3

+1, mais vous n'avez pas à sélectionner sélectionner "Modifier les 1000 premières lignes" (où est cette option dans SSMS 2005?). Vous avez seulement besoin d'ouvrir une table et de la coller dans une rangée vide. Soit dit en passant, il est simple et fonctionne si les noms des colonnes correspondent, mais cela prend 45 minutes (et non secondes) pour insérer 40.000 lignes avec cette méthode sur mon serveur (avec un insert-trigger actif). D'où c'est simple mais pas flexible et rapide. –

+0

@TimSchmelter, désolé, je voulais dire qu'il est très rapide à mettre en place et à démarrer, par rapport aux autres méthodes. Le temps d'exécution pourrait bien être 45 minutes, oui. J'ai mis à jour la réponse. – bzlm

+5

Voir http://www.mssqltips.com/sqlservertip/1430/import-excel-data-into-sql-server-using-copy-and-paste/ pour les photos –

13

Pour les références ultérieures:

Vous pouvez données de copier-coller à partir en Excel feuille à une table SQL en le faisant:

Sélectionnez les données dans Excel et appuyez sur Ctrl + C

  1. Sélectionnez les données dans Excel et appuyez sur Ctrl + C
  2. dans SQL Server Management studio clic droit sur la table et choisissez Modifier les 200 lignes
  3. Faites défiler jusqu'au bas et sélectionnez toute la ligne vide en cliquant sur l'en-tête de la ligne
  4. coller les données en appuyant sur Ctrl + V

Note: Souvent, les tables ont une première colonne qui est un ID-colonne avec un ID généré automatiquement/incrémenté. Lorsque vous collez vos données, il commence à insérer la colonne sélectionnée la plus à gauche dans Excel dans la colonne la plus à gauche dans SSMS, insérant ainsi des données dans la colonne ID. Pour éviter cela, conservez une colonne vide dans la partie la plus à gauche de votre sélection afin d'ignorer cette colonne dans SSMS. Cela entraînera l'insertion par SSMS des données par défaut, à savoir l'ID généré automatiquement. En outre, vous pouvez ignorer les autres colonnes en ayant des colonnes vides aux mêmes positions ordinales dans la sélection de feuille Excel que les colonnes à ignorer. Cela fera en sorte que SSMS insère la valeur par défaut (ou NULL lorsqu'aucune valeur par défaut n'est spécifiée).

+0

Ça me laisse juste faire une ligne à la fois. La minute où je sélectionne plus d'une ligne dans Excel, faire un collage dans SSMS fait exactement ... rien. J'ai essayé Ctrl + V, j'ai essayé de faire un clic droit + coller, j'ai essayé de le mettre dans le Bloc-notes et de supprimer la ligne blanche supplémentaire à la fin, j'ai essayé de mettre une colonne vide au début (comme vous aviez l'habitude de faire dans Enterprise Manager) ... rien ne fonctionne. – Martha

0

J'ai développé une macro VBA Excel pour couper et coller n'importe quelle sélection d'Excel dans SQL Server, en créant une nouvelle table. La macro est idéale pour les créations de table rapides et sales jusqu'à quelques milliers de lignes et plusieurs colonnes (elle peut théoriquement gérer jusqu'à 200 colonnes). La macro tente de détecter automatiquement les noms d'en-tête et d'affecter le type de données le plus approprié à chaque colonne (elle gère les colonnes varchar jusqu'à 1000 caractères).

Procédure d'installation recommandée:

  1. Assurez-vous que Excel est activé pour exécuter des macros. (Fichier-> Options-> Centre de Trust-> Paramètres Centre de Confiance-> Paramètres Macro-> Activer toutes les macros ..)
  2. Copiez le code VBA ci-dessous dans le module associé à votre classeur personnel (afin que la macro soit disponible pour toutes les feuilles de calcul)
  3. Affecter une combinaison de touches appropriée à la macro (je l'ai assigné Ctrl + Maj + X)
  4. Enregistrez votre classeur personnel

utilisation de macro

  1. Sélectionnez les cellules dans Excel (y compris la colonne il aders s'ils existent) à transférer vers SQL
  2. Appuyez sur la combinaison de mots-clés que vous avez affectée à l'exécution de la macro.
  3. Suivez les instructions. (Le nom de la table par défaut est ## Table)
  4. Collez le contenu du Presse-papiers dans une fenêtre SSMS et exécutez le code SQL généré. BriFri 238

code VBA:

Sub TransferToSQL() 
' 
' TransferToSQL Macro 
' This macro prepares data for pasting into SQL Server and posts it to the clipboard for inserting into SSMS 
' It attempts to automatically detect header rows and does a basic analysis of the first 15 rows to determine the most appropriate datatype to use handling text entries upto 1000 chars. 
' 
' Max Number of Columns: 200 
' 
' Keyboard Shortcut: Ctrl+Shift+X 
' 
' ver Date Reason 
' === ==== ====== 

' 1.6 06/2012 Fixed bug that prevented auto exit if no selection made/auto exit if blank Tablename entered or 'cancel' button pressed 
' 1.5 02/2012 made use of function fn_ColLetter to retrieve the Column Letter for a specified column 
' 1.4 02/2012 Replaces any Tabs in text data to spaces to prevent Double quotes being output in final results 
' 1.3 02/2012 Place the 'drop table if already exists' code into a separate batch to prevent errors when inserting new table with same name but different shape and > 100 rows 
' 1.2 01/2012 If null dates encountered code to cast it as Null rather than '00-Jan-1900' 
' 1.1 10/2011 Code to drop the table if already exists 
' 1.0 03/2011 Created 

Dim intLastRow As Long 
Dim intlastColumn As Integer 
Dim intRow As Long 
Dim intDataStartRow As Long 
Dim intColumn As Integer 
Dim strKeyWord As String 
Dim intPos As Integer 
Dim strDataTypeLevel(4) As String 
Dim strColumnHeader(200) As String 
Dim strDataType(200) As String 
Dim intRowCheck As Integer 
Dim strFormula(20) As String 
Dim intHasHeaderRow As Integer 
Dim strCellRef As String 
Dim intFormulaCount As Integer 
Dim strSQLTableName As String 
Dim strSQLTableName_Encap As String 
Dim intdataTypelevel As Integer 
Const strConstHeaderKeyword As String = "ID,URN,name,Title,Job,Company,Contact,Address,Post,Town,Email,Tele,phone,Area,Region,Business,Total,Month,Week,Year," 
Const intConstMaxBatchSize As Integer = 100 
    Const intConstNumberRowsToAnalyse As Integer = 100 
intHasHeaderRow = 0 

strDataTypeLevel(1) = "VARCHAR(1000)" 
strDataTypeLevel(2) = "FLOAT" 
strDataTypeLevel(3) = "INTEGER" 
strDataTypeLevel(4) = "DATETIME" 



' Use current selection and paste to new temp worksheet 

    Selection.Copy 
    Workbooks.Add  ' add temp 'Working' Workbook 
    ' Paste "Values Only" back into new temp workbook 
    Range("A3").Select ' Goto 3rd Row 
    Selection.PasteSpecial Paste:=xlFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False ' Copy Format of Selection 
    Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False ' Copy Values of Selection 
    ActiveCell.SpecialCells(xlLastCell).Select ' Goto last cell 
    intLastRow = ActiveCell.Row 
    intlastColumn = ActiveCell.Column 


' Check to make sure that there are cells which are selected 
If intLastRow = 3 And intlastColumn = 1 Then 
    Application.DisplayAlerts = False  ' Temporarily switch off Display Alerts 
    ActiveWindow.Close      ' Delete newly created worksheet 
    Application.DisplayAlerts = True  ' Switch display alerts back on 
    MsgBox "*** Please Make selection before running macro - Terminating ***", vbOKOnly, "Transfer Data to SQL Server" 
    Exit Sub 
End If 

' Prompt user for Name of SQL Server table 
strSQLTableName = InputBox("SQL Server Table Name?", "Transfer Excel Data To SQL", "##Table") 

' if blank table name entered or 'Cancel' selected then exit 
If strSQLTableName = "" Then 
    Application.DisplayAlerts = False  ' Temporarily switch off Display Alerts 
    ActiveWindow.Close      ' Delete newly created worksheet 
    Application.DisplayAlerts = True  ' Switch display alerts back on 
    Exit Sub 
End If 



' encapsulate tablename with square brackets if user has not already done so 
strSQLTableName_Encap = Replace(Replace(Replace("[" & Replace(strSQLTableName, ".", "].[") & "]", "[]", ""), "[[", "["), "]]", "]") 

' Try to determine if the First Row is a header row or contains data and if a header load names of Columns 
Range("A3").Select 
For intColumn = 1 To intlastColumn 
    ' first check to see if the first row contains any pure numbers or pure dates 
    If IsNumeric(ActiveCell.Value) Or IsDate(ActiveCell.Value) Then 
    intHasHeaderRow = vbNo 
    intDataStartRow = 3 
    Exit For 
    Else 
    strColumnHeader(intColumn) = ActiveCell.Value 
    ActiveCell.Offset(1, 0).Range("A1").Select ' go to the row below 
    If IsNumeric(ActiveCell.Value) Or IsDate(ActiveCell.Value) Then 
     intHasHeaderRow = vbYes 
     intDataStartRow = 4 
    End If 
    ActiveCell.Offset(-1, 0).Range("A1").Select ' go back up to the first row 
    If intHasHeaderRow = 0 Then  ' if still not determined if header exists: Look for header using keywords 
     intPos = 1 
     While intPos < Len(strConstHeaderKeyword) And intHasHeaderRow = 0 
     strKeyWord = Mid$(strConstHeaderKeyword, intPos, InStr(intPos, strConstHeaderKeyword, ",") - intPos) 
     If InStr(1, ActiveCell.Value, strKeyWord) > 0 Then 
      intHasHeaderRow = vbYes 
      intDataStartRow = 4 
     End If 
     intPos = InStr(intPos, strConstHeaderKeyword, ",") + 1 
     Wend 
    End If 
    End If 
    ActiveCell.Offset(0, 1).Range("A1").Select ' Goto next column 
Next intColumn 

' If auto header row detection has failed ask the user to manually select 
If intHasHeaderRow = 0 Then 
    intHasHeaderRow = MsgBox("Does current selection have a header row?", vbYesNo, "Auto header row detection failure") 
    If intHasHeaderRow = vbYes Then 
    intDataStartRow = 4 
    Else 
    intDataStartRow = 3 
    End If 

End If 




' *** Determine the Data Type of each Column *** 

' Go thru each Column to find Data types 
If intLastRow < intConstNumberRowsToAnalyse Then    ' Check the first intConstNumberRowsToAnalyse rows or to end of selection whichever is less 
    intRowCheck = intLastRow 
Else 
    intRowCheck = intConstNumberRowsToAnalyse 
End If 

For intColumn = 1 To intlastColumn 
    intdataTypelevel = 5 

    For intRow = intDataStartRow To intRowCheck 
    Application.Goto Reference:="R" & CStr(intRow) & "C" & CStr(intColumn) 
    If ActiveCell.Value = "" Then ' ignore blank (null) values 
    ElseIf IsDate(ActiveCell.Value) = True And Len(ActiveCell.Value) >= 8 Then 
     If intdataTypelevel > 4 Then intdataTypelevel = 4 
    ElseIf IsNumeric(ActiveCell.Value) = True And InStr(1, CStr(ActiveCell.Value), ".") = 0 And (Left(CStr(ActiveCell.Value), 1) <> "0" Or ActiveCell.Value = "0") And Len(ActiveCell.Value) < 10 Then 
     If intdataTypelevel > 3 Then intdataTypelevel = 3 
    ElseIf IsNumeric(ActiveCell.Value) = True And InStr(1, CStr(ActiveCell.Value), ".") >= 1 Then 
     If intdataTypelevel > 2 Then intdataTypelevel = 2 
    Else 
     intdataTypelevel = 1 
     Exit For 
    End If 
    Next intRow 
    If intdataTypelevel = 5 Then intdataTypelevel = 1 
    strDataType(intColumn) = strDataTypeLevel(intdataTypelevel) 
Next intColumn 


' *** Build up the SQL 
intFormulaCount = 1 
If intHasHeaderRow = vbYes Then  ' *** Header Row *** 
    Application.Goto Reference:="R4" & "C" & CStr(intlastColumn + 1) ' Goto next column in first data row of selection 
    strFormula(intFormulaCount) = "= ""SELECT " 
    For intColumn = 1 To intlastColumn 
    If strDataType(intColumn) = "DATETIME" Then   ' Code to take Excel Dates back to text 
     strCellRef = "Text(" & fn_ColLetter(intColumn) & "4,""dd-mmm-yyyy hh:mm:ss"")" 
    ElseIf strDataType(intColumn) = "VARCHAR(1000)" Then 
     strCellRef = "SUBSTITUTE(" & fn_ColLetter(intColumn) & "4,""'"",""''"")" ' Convert any single ' to double '' 
    Else 
     strCellRef = fn_ColLetter(intColumn) & "4" 
    End If 


    strFormula(intFormulaCount) = strFormula(intFormulaCount) & "CAST('""& " & strCellRef & " & ""' AS " & strDataType(intColumn) & ") AS [" & strColumnHeader(intColumn) & "]" 
    If intColumn < intlastColumn Then 
     strFormula(intFormulaCount) = strFormula(intFormulaCount) + ", " 
    Else 
     strFormula(intFormulaCount) = strFormula(intFormulaCount) + " UNION ALL """ 
    End If 
    ' since each cell can only hold a maximum no. of chars if Formula string gets too big continue formula in adjacent cell 
    If Len(strFormula(intFormulaCount)) > 700 And intColumn < intlastColumn Then 
     strFormula(intFormulaCount) = strFormula(intFormulaCount) + """" 
     intFormulaCount = intFormulaCount + 1 
     strFormula(intFormulaCount) = "= """ 
    End If 
    Next intColumn 

' Assign the formula to the cell(s) just right of the selection 
    For intColumn = 1 To intFormulaCount 
    ActiveCell.Value = strFormula(intColumn) 
    If intColumn < intFormulaCount Then ActiveCell.Offset(0, 1).Range("A1").Select ' Goto next column 
    Next intColumn 


' Auto Fill the formula for the full length of the selection 
    ActiveCell.Offset(0, -intFormulaCount + 1).Range("A1:" & fn_ColLetter(intFormulaCount) & "1").Select 
    If intLastRow > 4 Then Selection.AutoFill Destination:=Range(fn_ColLetter(intlastColumn + 1) & "4:" & fn_ColLetter(intlastColumn + intFormulaCount) & CStr(intLastRow)), Type:=xlFillDefault 

' Go to start row of data selection to add 'Select into' code 
    ActiveCell.Value = "SELECT * INTO " & strSQLTableName_Encap & " FROM (" & ActiveCell.Value 

' Go to cells above data to insert code for deleting old table with the same name in separate SQL batch 
    ActiveCell.Offset(-1, 0).Range("A1").Select ' go to the row above 
    ActiveCell.Value = "GO" 
    ActiveCell.Offset(-1, 0).Range("A1").Select ' go to the row above 
    If Left(strSQLTableName, 1) = "#" Then  ' temp table 
     ActiveCell.Value = "IF OBJECT_ID('tempdb.." & strSQLTableName & "') IS NOT NULL DROP TABLE " & strSQLTableName_Encap 
    Else 
     ActiveCell.Value = "IF OBJECT_ID('" & strSQLTableName & "') IS NOT NULL DROP TABLE " & strSQLTableName_Encap 
    End If 



' For Big selections (i.e. several 100 or 1000 rows) SQL Server takes a very long time to do a multiple union - Split up the table creation into many inserts 
    intRow = intConstMaxBatchSize + 4 ' add 4 to make sure 1st batch = Max Batch Size 
    While intRow < intLastRow 
    Application.Goto Reference:="R" & CStr(intRow - 1) & "C" & CStr(intlastColumn + intFormulaCount) ' Goto Row before intRow and the last column in formula selection 
    ActiveCell.Value = Replace(ActiveCell.Value, " UNION ALL ", ") a") ' Remove last 'UNION ALL' 

    Application.Goto Reference:="R" & CStr(intRow) & "C" & CStr(intlastColumn + 1) ' Goto intRow and the first column in formula selection 
    ActiveCell.Value = "INSERT " & strSQLTableName_Encap & " SELECT * FROM (" & ActiveCell.Value 
    intRow = intRow + intConstMaxBatchSize ' increment intRow by intConstMaxBatchSize 
    Wend 


    ' Delete the last 'UNION AlL' replacing it with brackets to mark the end of the last insert 
    Application.Goto Reference:="R" & CStr(intLastRow) & "C" & CStr(intlastColumn + intFormulaCount) 
    ActiveCell.Value = Replace(ActiveCell.Value, " UNION ALL ", ") a") 

    ' Select all the formula cells 
    ActiveCell.Offset(-intLastRow + 2, 1 - intFormulaCount).Range("A1:" & fn_ColLetter(intFormulaCount + 1) & CStr(intLastRow - 1)).Select 
Else ' *** No Header Row *** 
    Application.Goto Reference:="R3" & "C" & CStr(intlastColumn + 1) ' Goto next column in first data row of selection 
    strFormula(intFormulaCount) = "= ""SELECT " 

    For intColumn = 1 To intlastColumn 
    If strDataType(intColumn) = "DATETIME" Then 
     strCellRef = "Text(" & fn_ColLetter(intColumn) & "3,""dd-mmm-yyyy hh:mm:ss"")" ' Format Excel dates into a text Date format that SQL will pick up 
    ElseIf strDataType(intColumn) = "VARCHAR(1000)" Then 
     strCellRef = "SUBSTITUTE(" & fn_ColLetter(intColumn) & "3,""'"",""''"")"   ' Change all single ' to double '' 
    Else 
     strCellRef = fn_ColLetter(intColumn) & "3" 
    End If 

    ' Since no column headers: Name each column "Column001",Column002".. 
    strFormula(intFormulaCount) = strFormula(intFormulaCount) & "CAST('""& " & strCellRef & " & ""' AS " & strDataType(intColumn) & ") AS [Column" & CStr(intColumn) & "]" 
    If intColumn < intlastColumn Then 
     strFormula(intFormulaCount) = strFormula(intFormulaCount) + ", " 
    Else 
     strFormula(intFormulaCount) = strFormula(intFormulaCount) + " UNION ALL """ 
    End If 

    ' since each cell can only hold a maximum no. of chars if Formula string gets too big continue formula in adjacent cell 
    If Len(strFormula(intFormulaCount)) > 700 And intColumn < intlastColumn Then 
     strFormula(intFormulaCount) = strFormula(intFormulaCount) + """" 
     intFormulaCount = intFormulaCount + 1 
     strFormula(intFormulaCount) = "= """ 
    End If 
    Next intColumn 

    ' Assign the formula to the cell(s) just right of the selection 
    For intColumn = 1 To intFormulaCount 
    ActiveCell.Value = strFormula(intColumn) 
    If intColumn < intFormulaCount Then ActiveCell.Offset(0, 1).Range("A1").Select ' Goto next column 
    Next intColumn 

' Auto Fill the formula for the full length of the selection 
    ActiveCell.Offset(0, -intFormulaCount + 1).Range("A1:" & fn_ColLetter(intFormulaCount) & "1").Select 
    If intLastRow > 4 Then Selection.AutoFill Destination:=Range(fn_ColLetter(intlastColumn + 1) & "3:" & fn_ColLetter(intlastColumn + intFormulaCount) & CStr(intLastRow)), Type:=xlFillDefault 

' Go to start row of data selection to add 'Select into' code 
    ActiveCell.Value = "SELECT * INTO " & strSQLTableName_Encap & " FROM (" & ActiveCell.Value 

' Go to cells above data to insert code for deleting old table with the same name in separate SQL batch 
    ActiveCell.Offset(-1, 0).Range("A1").Select ' go to the row above 
    ActiveCell.Value = "GO" 
    ActiveCell.Offset(-1, 0).Range("A1").Select ' go to the row above 
    If Left(strSQLTableName, 1) = "#" Then  ' temp table 
     ActiveCell.Value = "IF OBJECT_ID('tempdb.." & strSQLTableName & "') IS NOT NULL DROP TABLE " & strSQLTableName_Encap 
    Else 
     ActiveCell.Value = "IF OBJECT_ID('" & strSQLTableName & "') IS NOT NULL DROP TABLE " & strSQLTableName_Encap 
    End If 

    ' For Big selections (i.e. serveral 100 or 1000 rows) SQL Server takes a very long time to do a multiple union - Split up the table creation into many inserts 
    intRow = intConstMaxBatchSize + 3  ' add 3 to make sure 1st batch = Max Batch Size 
    While intRow < intLastRow 
    Application.Goto Reference:="R" & CStr(intRow - 1) & "C" & CStr(intlastColumn + intFormulaCount) ' Goto Row before intRow and the last column in formula selection 
    ActiveCell.Value = Replace(ActiveCell.Value, " UNION ALL ", ") a") ' Remove last 'UNION ALL' 

    Application.Goto Reference:="R" & CStr(intRow) & "C" & CStr(intlastColumn + 1) ' Goto intRow and the first column in formula selection 
    ActiveCell.Value = "INSERT " & strSQLTableName_Encap & " SELECT * FROM (" & ActiveCell.Value 
    intRow = intRow + intConstMaxBatchSize ' increment intRow by intConstMaxBatchSize 
    Wend 

    ' Delete the last 'UNION AlL' 
    Application.Goto Reference:="R" & CStr(intLastRow) & "C" & CStr(intlastColumn + intFormulaCount) 
    ActiveCell.Value = Replace(ActiveCell.Value, " UNION ALL ", ") a") 

    ' Select all the formula cells 
    ActiveCell.Offset(-intLastRow + 1, 1 - intFormulaCount).Range("A1:" & fn_ColLetter(intFormulaCount + 1) & CStr(intLastRow)).Select 
End If 


' Final Selection to clipboard and Cleaning of data 
Selection.Copy 
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False    ' Repaste "Values Only" back into cells 
Selection.Replace What:="CAST('' AS", Replacement:="CAST(NULL AS", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False ' convert all blank cells to NULL 
Selection.Replace What:="'00-Jan-1900 00:00:00'", Replacement:="NULL", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False ' convert all blank Date cells to NULL 
Selection.Replace What:="'NULL'", Replacement:="NULL", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False ' convert all 'NULL' cells to NULL 
Selection.Replace What:=vbTab, Replacement:=" ", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False  ' Replace all Tabs in cells to Space to prevent Double Quotes occuring in the final paste text 
Selection.Copy 


MsgBox "SQL Code has been added to clipboard - Please Paste into SSMS window", vbOKOnly, "Transfer to SQL" 

Application.DisplayAlerts = False  ' Temporarily switch off Display Alerts 
ActiveWindow.Close      ' Delete newly created worksheet 
Application.DisplayAlerts = True  ' Switch display alerts back on 



End Sub 




Function fn_ColLetter(Col As Integer) As String 

Dim strColLetter As String 

If Col > 26 Then 
    ' double letter columns 
    strColLetter = Chr(Int((Col - 1)/26) + 64) & _ 
     Chr(((Col - 1) Mod 26) + 65) 
Else 
    ' single letter columns 
    strColLetter = Chr(Col + 64) 
End If 
fn_ColLetter = strColLetter 
End Function 
2

Excel

  1. Dans Excel, mettez en surbrillance et copier les données que vous souhaitez coller dans SQL.

SQL

  1. Créer la table avec les noms de colonnes souhaitées et donner un nom vous tableau. * Assurez-vous que Identity Specification est Oui, de sorte qu'il incrémente automatiquement votre colonne Identité .
  2. Trouvez votre table, faites un clic droit dessus et choisissez Edit Top 200 Rows dans la boîte de dialogue.
  3. Faites un clic droit sur la ligne vide avec le signe * et sélectionnez Coller dans la boîte de dialogue boîte

enter image description here

Questions connexes