I have a stored procedures that will import 28 CSV files with different columns layout for each one, into their own table in SQL Server 2008 and a master stored procedure which will execute the other 28 store procedures.All the CSV files are stored on the network drive in one folder.The naming of these files will vary from week to week and I don’t want to manually change the names in the stored procedures. Each table name has a unique Identifier F1 to F28 that will be a constant before the rest of the name for example – F1_country23F2_region12Can I use the unique Identifier to add an wildcard or variable to the stored proc so it will pick any file in the folder for example with "F1" or "F2" meaning format layout 1 or 2 and use the correct stored procedure like below? WHEN 'F1' THEN 'usp_F1_ImportScript' WHEN 'F2' THEN 'usp_F2_ImportScript'
Example SQL scripts so far –Create PROC [dbo].[usp_F1_ImportScript]AS -- Check if template table already exists and if it does then delete the tableIF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CSVTest]') AND type in (N'U'))DROP TABLE dbo.CSVTest-- Create a new template tableCREATE TABLE CSVTest(TCODE Varchar (5),PSPNR Varchar (255),ZZLOC Varchar (255),ZZPLN_QTY Varchar (255))-- Load data into tableBULKINSERT CSVTestFROM 'C:\Users\Desktop\F1_Book1.csv' WITH(FIRSTROW = 2, -- Removes the Header RowFIELDTERMINATOR = ',',ROWTERMINATOR = '\n')
Create PROC [dbo].[usp_F1_ImportScript]AS -- Check if template table already exists and if it does then delete the tableIF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[VCOST]') AND type in (N'U'))DROP TABLE dbo.VCOST-- Create a new template tableCREATE TABLE VCOST(TCODE Varchar (4),PSPNR Varchar (25),ZZOBJ_NO Varchar (10))-- Load data into tableBULKINSERT VCOSTFROM 'C:\Users\Desktop\F2_Book2.csv' WITH(FIRSTROW = 2, -- Removes the Header RowFIELDTERMINATOR = ',',ROWTERMINATOR = '\n')
CREATE PROCEDURE [dbo].[usp_FilePicker] (@FileName VARCHAR(255))AS--check if @FileName is nullIF @FileName IS NULLBEGINSELECT 'No Files Match' AS ERRORRETURNEND--Declare our dynamic sql holderDECLARE @Cmd VARCHAR(MAX)-- set up exec commandSET @Cmd = 'EXEC ' --Get the stored procedure to run add when statements for eachSET @Cmd = @Cmd + CASE @FileName WHEN 'F1_Book1.csv' THEN 'usp_F1_ImportScript' WHEN 'F2_Book2.csv' THEN 'usp_F2_ImportScript' END --Execute the Stored Procedure EXEC( @Cmd )EXEC usp_FilePicker 'F1_Book2.csv'EXEC usp_FilePicker 'F2_Book1.csv'