Can you please help me to write and execute a dynamic SQL statement in a stored procedure?
I need to import many files in my database. To do this job I use a "Bulk Insert". So I have created a parameters table to store parameters I need to create a dynamic "Bulk Insert" depending file I insert.
This table is for the users when they want to modify or add a new file to insert in the table.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_Alim_Sas_MCP_Files]
@FileSource NVARCHAR(100)
AS
BEGIN
DECLARE @SQL NVARCHAR(4000)
DECLARE @SQL_ NVARCHAR(4000)
SET @SQL =''
SELECT @SQL + 'TRUNCATE TABLE [Ods].[SRC_MCP_Files];
BULK INSERT [Ods].[Src_MCP_Files]
FROM ''' + [FileSource] + '''
WITH
(DATA_SOURCE = ''' + [DataSource] +''',
DATAFILETYPE = ''' + [DataFileType] + ''',
FIELDTERMINATOR = ''' + [FieldTerminator] + ''',
ROWTERMINATOR = ''' + [RowTerminator]+ ''',
CODEPAGE = ' + CAST([CodePage] AS NVARCHAR(10))+ ',
FIRSTROW = ' + CAST([FirstRow] AS NVARCHAR(10)) +',
TABLOCK
);
INSERT INTO [Ods].[Sas_MCP_Files]
(ResponseCode, [CountryCode], [CountryLabel], Code, Label,
Lang, Lang_2, [DateExtraction], [IdDateExtraction])
SELECT ResponseCode = ResponseCode+''_''+ [CountryCode] + ''_''+Code ,
[CountryCode]
,[CountryLabel]
,Code
, Label
, Lang
, Lang_2
,[DateExtraction]= getdate ()
,[IdDateExtraction] = convert(int,convert(varchar,getdate(),112))
FROM [Ods].[SRC_MCP_Files] '
FROM [Config].[File_Parameters]
WHERE FileSource = @FileSource
EXEC (@SQL)
END;
EXEC [dbo].[usp_Alim_Sas_MCP_Files] 'temp/mcp/Accompagnists_2.csv'
I expect that the stored procedure executes the Bulk Insert script inside it.