2008-11-25 13 views
47

Tengo un montón de filas en Excel que quiero pegar en una nueva tabla en MS SQL. ¿Hay una manera simple?Pegar datos de MS Excel en SQL Server

+0

esto no parece estar relacionada con la programación-- estás tratando de hacer esto con VBA ¿o algo? – warren

+0

No, solo grandes cantidades de datos llegan adhoc como excel o fácilmente, 'exelable' – Bajji

+0

Esto http://dotnetstories.wordpress.com/2008/05/24/copy-paste-data-from-excel-to-sql- server-2005/funcionó para mí –

Respuesta

29

He utilizado esta técnica con éxito en el pasado:

Using Excel to generate Inserts for SQL Server

(...) Pasar una columna (o lo utilizan para las notas) y escriba algo como lo siguiente fórmula en la que:

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

Ahora usted tiene su instrucción de inserción de una tabla con su clave principal (PK), un entero y una cadena Unicode. (...)

+1

La respuesta de bzlm es más adecuada para la pregunta. ¡Este es un pequeño descubrimiento, pero la mayoría de los casos, el clic derecho de bzlm y el pasado! – ThinkCode

+0

Esto es más rápido y simple: http://www.mssqltips.com/sqlservertip/1430/import-excel-data-into-sql-server-using-copy-and-paste/ –

+0

Copiar y pegar no funcionó para yo, ni tampoco el comando 'OPENROWSET'. ¡La única forma fue la respuesta de Galwegian! –

2

La manera más simple es crear una columna calculada en XLS que generaría la sintaxis de la instrucción de inserción. Luego copie estas inserciones en un archivo de texto y luego ejecútelas en el SQL. Las otras alternativas son comprar complementos de conectividad de bases de datos para Excel y escribir el código de VBA para lograr lo mismo.

0

Si la interfaz funciona como lo hizo la última vez que la usé, puede seleccionar la región en Excel, copiarla, abrir SQL Server y pegar los datos en la tabla como lo haría con Access.

O podría configurar un enlace ODBC entre Excel y SQL Server.

1

Creo que algunas bases de datos pueden importar datos de archivos CSV (valores separados por comas), que puede exportar de exel. O al menos es bastante fácil usar un analizador csv (encuentre uno para su idioma, no intente crearlo usted mismo, es más difícil de lo que parece) para importarlo a la base de datos.

No estoy familiarizado con MS SQL pero no me sorprendería si lo admite directamente.

En cualquier caso, creo que el requisito debe ser que la estructura en la hoja Exel y la tabla de la base de datos sea similar.

-1

¿por qué no usar el asistente de exportación/importación en SSMS?

50

Si tiene SQL Server Management Studio, puede simplemente copiar desde Excel y pegar en la tabla en Management Studio, usando su mouse. Solo

  1. Ve a la tabla en la que deseas pegar.
  2. Seleccione "Editar las 200 mejores filas".
  3. Haga clic derecho en cualquier lugar y seleccione Pegar.

Antes de hacer esto, debe hacer coincidir las columnas entre Excel y Management Studio. Además, debe colocar las columnas no editables últimas (más a la derecha) utilizando Table Designer en Management Studio.

Todo el procedimiento lleva unos segundos (hasta configuración e inicio - no necesariamente para ejecutar) y no requiere ninguna instrucción SQL.

+3

+1, pero no tiene que seleccionar seleccionar "Editar las 1000 primeras filas" (¿dónde está esa opción en SSMS 2005?). Solo necesita abrir una tabla y pegarla en una fila vacía. Por cierto, es simple y funciona si los nombres de las columnas coinciden entre sí, pero lleva 45 minutos (y no segundos) insertar 40,000 filas con este método en mi servidor (con un insert-trigger activado). Por lo tanto, es simple pero no flexible y rápido. –

+0

@TimSchmelter, lo siento, quise decir que es muy rápido de configurar y comenzar, en comparación con los otros métodos. El tiempo de ejecución podría ser de 45 minutos, sí. He actualizado la respuesta. – bzlm

+5

Consulte http://www.mssqltips.com/sqlservertip/1430/import-excel-data-into-sql-server-using-copy-and-paste/ para imágenes –

-1

¿No puede usar el código VBA para copiar desde Excel y pegarlo en operaciones de SSMS?

13

Para futuras referencias:

Se pueden copiar y pegar los datos de en una hoja Excel a un SQL-mesa al hacerlo:

Seleccione de los datos en Excel y pulse Ctrl + C.

  1. seleccionar los datos en Excel y pulse Ctrl + C
  2. en SQL Server Management Studio, haga clic derecho en la tabla y seleccione Editar Top 200 Filas
  3. Vaya a la parte inferior y seleccionar toda la fila vacía haciendo clic en el encabezado de la fila
  4. pegar los datos presionando Ctrl + V

Nota: A menudo, las mesas tienen una primera columna que es una ID-column con un ID autogenerado/incrementado. Cuando pegue sus datos, comenzará a insertar la columna seleccionada más a la izquierda en Excel en la columna más a la izquierda en SSMS, insertando datos en la columna ID. Para evitar eso, mantenga una columna vacía en la parte más a la izquierda de su selección para omitir esa columna en SSMS. Eso dará como resultado que SSMS inserte los datos predeterminados, que es el ID generado automáticamente. Además, puede omitir otras columnas al tener columnas vacías en las mismas posiciones ordinales en la selección de hojas de Excel que aquellas columnas que se omiten. Eso hará que SSMS inserte el valor predeterminado (o NULL donde no se especifica ningún valor predeterminado).

+0

Solo me permite hacer esto una fila a la vez. En el momento en que selecciono más de una fila en Excel, hacer un pegado en SSMS no hace exactamente ... nada. He intentado Ctrl + V, he intentado con el botón derecho + pegar, he intentado ponerlo en el Bloc de notas primero y eliminar la línea en blanco adicional desde el final. Intenté poner una columna en blanco al principio (como solía tener que hacer en Enterprise Manager) ... nada funciona. – Martha

0

He desarrollado una macro de Excel VBA para cortar y pegar cualquier selección de Excel en SQL Server, creando una nueva tabla. La macro es ideal para creaciones de tablas rápidas y sucias de hasta miles de filas y múltiples columnas (teóricamente puede administrar hasta 200 columnas). La macro intenta detectar automáticamente nombres de encabezado y asignar el tipo de datos más apropiado a cada columna (maneja columnas varchar hasta 1000 caracteres).

procedimiento de configuración recomendada:

  1. Asegúrese de Excel está habilitado para ejecutar macros. (Archivo-> Opciones-> Centro de confianza-> Configuración del Centro de confianza-> Configuración de macros-> Habilitar todas las macros ...)
  2. Copie el código de VBA a continuación en el módulo asociado a su libro de trabajo personal (para que la macro esté disponible) para todas las hojas de trabajo)
  3. asignar una combinación de teclas apropiada a la macro (he asignado Ctrl Shift X)
  4. guardar su libro personal

el uso de macro

  1. Seleccione las celdas en Excel (incluyendo la columna él aders si existen) para ser transferidos a SQL
  2. Presione la combinación de palabras clave asignadas que ha asignado para ejecutar la macro
  3. Siga las instrucciones. (El nombre de tabla predeterminado es ## Tabla)
  4. Pegue los contenidos del portapapeles en una ventana SSMS y ejecute el código SQL generado. BriFri 238

código 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. En Excel, seleccionar y copiar los datos que desea pegar en SQL.

SQL

  1. crear la tabla con los nombres de columna deseada y le dará un nombre de tabla. * Asegúrese de que Identity Specification es Sí, por lo que aumentará automáticamente su columna de Identidad .
  2. Busque su tabla y haga clic derecho en ella y elija Edit Top 200 Rows desde el cuadro de diálogo.
  3. Haga clic derecho sobre la fila vacía con el signo * y seleccione Pegar en el cuadro de diálogo de

enter image description here

Cuestiones relacionadas