How to cast variables in T-SQL for bulk insert?

后端 未结 6 1517
面向向阳花
面向向阳花 2020-11-30 10:20

The following code gives an error (its part of a T-SQL stored procedure):

-- Bulk insert data from the .csv file into the staging table.
DECLARE @CSVfile nva         


        
相关标签:
6条回答
  • 2020-11-30 10:32

    A string literal is required.

    http://msdn.microsoft.com/en-us/library/ms188365.aspx

    You could use dynamic sql to generate the string literal.

    0 讨论(0)
  • 2020-11-30 10:38

    As I know only literal string is required in the from. In that case you have to write a dynamic query to use bulk insert

    declare @q nvarchar(MAX);
    set @q=
        'BULK INSERT [TStagingTable]
        FROM '+char(39)+@CSVfile+char(39)+'
        WITH
        (
        FIELDTERMINATOR = '','',
        ROWTERMINATOR = ''\n'',
        FIRSTROW = 1  
        )'
    exec(@q)
    
    0 讨论(0)
  • 2020-11-30 10:45

    Have you tried with dynamic SQL?

    SET @SQL = "BULK INSERT TmpStList FROM '"+@PathFileName+"' WITH (FIELDTERMINATOR = '"",""') "
    

    and then

    EXEC(@SQL)
    

    Ref.: http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file

    0 讨论(0)
  • 2020-11-30 10:48

    you have to engage in string building & then calling EXEC() or sp_executesql BOL has an example:

    DECLARE @bulk_cmd varchar(1000)
    SET @bulk_cmd = 'BULK INSERT AdventureWorks2008R2.Sales.SalesOrderDetail
    FROM ''<drive>:\<path>\<filename>'' 
    WITH (ROWTERMINATOR = '''+CHAR(10)+''')'
    EXEC(@bulk_cmd)
    
    0 讨论(0)
  • 2020-11-30 10:51

    Most of the time the variable i'm looking for in a file name is the date, and this one works perfectly for bulk inserting files with date, for use such as in a daily job. Change as per your need, date format, table name, file path, file name and delimiters.

        DECLARE @DT VARCHAR (10)
        DECLARE @INSERT VARCHAR (1000)
        SET @DT = (CONVERT(VARCHAR(10),GETDATE()-1,120))
        SET @INSERT = 'BULK INSERT dbo.table FROM ''C:\FOLDER\FILE'+@DT+'.txt'''+' WITH  (FIRSTROW=2, FIELDTERMINATOR=''\t'', ROWTERMINATOR=''\n'')'
        EXEC (@INSERT);
    
    0 讨论(0)
  • 2020-11-30 10:56

    Can you try FROM ' + @CSVfile + '

    0 讨论(0)
提交回复
热议问题