I have a bunch of CSV files to import and so I've created BCPFORMAT files in XML. These are all working well and I can import the data correctly.
I'm now trying to create a stored procedure (which I've never done before) that accepts three parameters:
1. The table name
2. The path to the CSV file
3. The path to the BCPFORMAT file
CREATE PROC dbo.usp_import_csv
@table_name nvarchar(100), /* name of table to import into */
@csv_path nvarchar(1000), /* path to csv file */
@bcp_format_path nvarchar(1000) /* path to BCPFORMAT file */
AS
BEGIN
DELETE FROM @table_name
BULK INSERT @table_name
FROM @csv_path
WITH (FIRSTROW = 1 , FORMATFILE = @bcp_format_path)
END
EXEC dbo.usp_import_cttp 'dbo.new_table', 'C:\temp\new_table.csv', 'C:\Temp\new_table.xml'
I get the message Incorrect syntax near '@table_name'. so I'm obviously not doing something quite right. But I can't figure out what that is...
ANSWER DERIVED FROM BELOW
CREATE PROC dbo.usp_import_cttp
@table_name nvarchar(100), /* table to import into */
@csv_path nvarchar(1000), /* folder containing latest NZULM data files */
@bcp_format_path nvarchar(1000) /* folder containing BCPFORMAT files used to explain csv files */
AS
BEGIN
EXEC sp_executesql 'DELETE FROM @table_name', @table_name;
EXEC sp_executesql 'BULK INSERT @table_name
FROM @csv_path
WITH (FIRSTROW = 1 , FORMATFILE = @bcp_format_path)',
@table_name,
@csv_path,
@bcp_format_path;
END
'BULK INSERT ' + quotename(@table_name) + ' FROM @csv_path ...'