简体   繁体   中英

How to get reference of input files in scripts under VS2012 Database project

We have a solution in which we added a database project. This project creates database tables and inserts data when published. I have added a post deployment script in which I call a Postcode.sql script that inserts postcodes into one of our tables. Everything works except that when I would like to specify a CSV file as input for bulk insert, no matter what I do I always get a "The system cannot find the path specified." exception. The folder structure looks like this:

[DatabaseProject]
[InputFiles] //folder
- Postcodes.csv
[PostDeploymentScripts] //folder
- Postcode.PostDeployment.sql //this will call the Postcode.sql
- Postcode.sql

This is the (currently test) sql script in Postcode.sql:

DECLARE @Count int;
SELECT @Count = Count(*) FROM Postcode;
IF(@Count = 0)
BEGIN
BULK INSERT Postcode
FROM '.\InputFiles\Postcodes.csv'
WITH
(
ROWTERMINATOR = '\n'
)
END
GO

I changed the from to "FROM 'c:\\TFS\\Project\\InputFiles\\Postcodes.csv'" to make it work, but I need a path here that will work on the other developer's machine as well, because I am sure they use different folder for storing the solution.

So the question is: what is the proper format - if there are any - of pointing to that Postcodes.csv in an sql script file?

Well, I have decided not to use sql script file, but to run the command immediately from the deployment script like this (I have made the insert script better and shorter):

-- Insert Postcodes
IF(NOT EXISTS(SELECT * FROM Postcode)) BEGIN
    BULK INSERT Postcode
    FROM [$(PostcodesFilePath)]
    WITH (ROWTERMINATOR = '\n')
END

To be able to run this I had to specify a variable called PostcodesFilePath. To do this:

1. Open properties of the project.
2. Go to SQLCMD variable tab.
3. Add $(PostcodesFilePath) to the list of variable and set ONLY the default
   value column to $(ProjectDir)InputFiles\Postcodes.csv
4. To make sure the value is good, just save your project, close properties
   and reopen it. The default column will contain the full path to your csv.
5. If you would like to run the post deployment script, just publish your
   database project. In case you have build errors it is possible that you need
   to click on 'SQLCMD mode' button in your post deployment editor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM