Search code examples
sqlsql-serverinsertbulk

How to store file path as parameter to import data in a table via bulk statement


I am currently trying to save a file path as a parameter so I don't have to every time declare it because file path is always the same and if I need to change it I can do it in one place in my declared variable. Only thing that changes is the .csv name of a file. Is it even possible to do that. I was able to write insert with dynammic SQL but I want something like that:

DECLARE @filePath NVARCHAR(200) = 'C:\Users\Folder\' --declare "constant" file path

DECLARE @SQL NVARCHAR(MAX) = ''
    SET @SQL = N'
    BULK INSERT product
      FROM ''' +@filePath + 'productName.csv' + ''' -- different .csv name
      WITH (
        FIELDTERMINATOR = '';'',    
        FIRSTROW=2,                 
        CODEPAGE = ''1250''
            )'
EXEC sp_executesql @SQL

Second table

-- in the previous step I already declare file path so I don't have to do it again.

DECLARE @SQL NVARCHAR(MAX) = ''
    SET @SQL = N'
    BULK INSERT store
      FROM ''' +@filePath + 'storeName.csv' + ''' -- different .csv name
      WITH (
        FIELDTERMINATOR = '';'',    
        FIRSTROW=2,                 
        CODEPAGE = ''1250''
            )'
EXEC sp_executesql @SQL

Solution

  • It's not clear exactly what your issue is, however if you want to declare a variable and have it survive / be available over multiple separate batches then you can save it in session_context

    Declare @MyVar varchar(50) = 'some string';
    
    exec sp_set_session_context N'RememberMe', @MyVar;
    
    GO
    
    Declare @MyVar varchar(50);
    
    set @MyVar = (Convert(varchar(50), Session_Context(N'RememberMe')));
    select @MyVar;