SSMS: How to import (Copy/Paste) data from excel

前端 未结 5 1618
轻奢々
轻奢々 2020-12-22 07:17

How to Copy/Paste following delimited data (by default delimited with tab) from excel:

declare @t_values   nvarchar(max)   =                   
N\'                   


        
5条回答
  •  隐瞒了意图╮
    2020-12-22 07:51

    Please try following:

    -- NB! Script do NOT write any ifo to any table
    -- to perform insert please copy/paste script output and execute
    
    declare @tbl_name   nvarchar(128)   = '#insertTable';     -- Destination Table Name + [(column names)]
    declare @dlm        nvarchar(128)   = char(9);  -- Delimiter: HT = char(9) = HorizontalTab
    declare @tbl        nvarchar(max)   =               -- Paste Table Values here (from excel for instance)
    N'NULL    490366  NULL    NULL
    NULL    490400  NULL    NULL
    NULL    490402  NULL    NULL
    483061  490404  10  abc1
    NULL    490406  NULL    NULL
    9766167 490408  3   abc2'
    ;
    
    select N'insert into '
            + @tbl_name             -- table name
            + ' VALUES(' 
            + replace               -- replace 'NULL' by NULL
              ( '''' 
                 + replace          -- surround values by quotes 'value1','value2'...
                   (    value
                   ,    @dlm        -- Delimiter: HT = char(9) = HorizontalTab
                   ,    ''','''
                   ) 
                 + ''''
              , '''NULL'''  
              , 'NULL'      
              )                                              
            + ');' as insertquery
    --into #t 
    from fn_split_string            -- insert Line per Row into table
         (  replace                 -- replace CR + LF by LF  (CR - Carriage Return, LF - Line Feed)
            (   @tbl                -- Paste Table Values here (from excel for instance)
            , char(13)+char(10)     -- CR + LF
            , char(10)              -- LF
            )
         ,char(10)
         ) 
    where len(value)>0              -- skip empty rows
    

提交回复
热议问题