How to Copy/Paste following delimited data (by default delimited with tab) from excel:
declare @t_values nvarchar(max) =
N\'
Snippet for SELECT INTO
:
SelectTable
Prepare Copy/Paste Excel data for exporting to temp table
Denis Sipchenko
SurroundsWith
t_name #t Destination Table Name
col_nm NULL comma separated COLUMN Names
selected CopyPasteExcelTableHere copy/paste Excel data here
delimiter char(9) Column Delimiter: HT = char(9) = HorizontalTab
eol N'
' EndOfLine
1st row contains column names
BEGIN
SET @tmp_clm_name = left(@tbl, charindex(char(10), @tbl)-1);
SET @tbl = stuff(@tbl, 1, len(@tmp_clm_name)+1, '');
SET @tmp_clm_name = '[' + REPLACE(@tmp_clm_name, @dlm, '],[') + ']';
END
;
SET @FirstRow = N'IF OBJECT_ID(''tempdb..'+@tmp_tbl_name+''') IS NOT NULL DROP TABLE '+ @tmp_tbl_name + ';'
+ @eol + N'-- select '+ @tmp_clm_name+' from $t_name$;'
+ @eol + N'SELECT * INTO ' + @tmp_tbl_name + N' FROM '
+ @eol + N'(VALUES '
;
SET @LastRow = N') t('+ @tmp_clm_name +');'
;
;with v as
( select --row_number() over(order by insertquery),
',('
+ replace -- replace 'NULL' by NULL
( ''''
+ replace -- surround values by quotes 'value1','value2'...
( value
, @dlm -- Delimiter: HT = char(9) = HorizontalTab
, ''','''
)
+ ''''
, '''NULL'''
, 'NULL'
)
+ ')' as insertvalues
--into #t
from string_split(@tbl, char(10)) -- insert Line per Row into table
where len(value)>0 -- skip empty rows
),
rv as -- adding RowID column (have to identify 1st row to remove 1st character)
( select (ROW_NUMBER() OVER(ORDER BY insertvalues)) as RowID, *
from v
)
select 1 as RowID , @FirstRow as SelectInto
union all select 1 + RowID , case when RowID=1 then stuff(insertvalues,1,1,' ') else insertvalues end from rv
union all select 2 +(select count(*) from rv), @LastRow
order by RowID
$end$
]]>
Screen: