sql server export Excel to disk via T-SQL

The ALTER  PROCEDURE  [ dbo ] . [ Pro_ImportExcelByTime ] 
    
AS 
BEGIN 
    - the first step to open the advanced features 
    EXEC sp_configure ' Show advanced Options ' , 1 ; 
    
    RECONFIGURE ; 
    
    EXEC sp_configure ' the xp_cmdshell ' , 1 
    RECONFIGURE ; 
    

    - the second step, bcp export excel 

    DECLARE  @file_path   nvarchar ( 50 ), @file_name  nvarchar ( 500 ), @exec_sql nvarchar ( 4000 )
     SET  @file_path  =  ' D: \ '   - defined export excel absolute path 
    DECLARE  @index  int 
    SELECT  @index = MAX (AutoID) from TestB.dbo.seed WHERE  the CONVERT ( VARCHAR ( 10 ), CreateTime, 120 ) = the CONVERT ( VARCHAR ( 10 ), GETDATE (), 120 )
     IF  @index  IS  null  or  @index =0 
    the begin 
        SET  @index = . 1 
    End 
    the else 
    the begin 
        SET  @index = @index + . 1 
    End 
    - export file name 
    SET  @file_name  =  ' Export Excel ( ' + the CONVERT ( nvarchar ( 10 ), @index ) + ' ) ' + the CONVERT ( nvarchar ( 50 ), GETDATE (), 112 ) + ' * .xls '   -Excel file name defined 
    DECLARE  @colName  nvarchar ( 10 ), @proPrice  nvarchar ( 10 ), @proNumber  nvarchar ( 10 ), @proDescript  nvarchar ( 200 is ), @proCreateTime  nvarchar ( 10 )
     SET  @colName = ' name ' 
    SET  @proPrice = ' price ' 
    SET  @proNumber = ' number ' 
    SET  @proDescript = 'Description ' 
    SET  @proCreateTime = ' Created ' 
    - data source sql statement 
    SET  @exec_sql  =  ' SELECT '' ' + @colName + ' '' , '' ' + @proPrice + ' '' , '' ' + @proNumber + '' ' , ' '' + @proDescript + '' ' , ' '' + @proCreateTime + '' 'All SELECT proname Union, Convert (nvarchar (10), proPrice), Convert (nvarchar (10), proNumber), proDescript, Convert (nvarchar (10), proCreateTime, 120) from testA.dbo.project1 '   - defined query sql statement; full path of a data table required for use; SQL statement must complete row 
    SET  @exec_sql  =  ' BCP " ' + @exec_sql + ' " the queryout " ' + @file_path + '' + @file_name + ' " -T -C -S "LAPTOP-AUVHR4RD" -U "SA" -P "123456" ' ;
    Exec the xp_cmdshell @exec_sql  
    - Modify identification 
    INSERT  INTO TestB.dbo.seed (A)values ( ' first ' + Convert ( VARCHAR ( 10 ), @index ) + ' times export ' ) 

    - a third step, the advanced features off 
    EXEC the sp_configure ' the xp_cmdshell ' , 0 
    the RECONFIGURE ; 

    EXEC the sp_configure ' Show advanced Options ' , 0 ; 
    
    the RECONFIGURE ; 
    
the END

 

Guess you like

Origin www.cnblogs.com/yuanyanyan/p/12050150.html