简体   繁体   English

如何在VS2012数据库项目下的脚本中获取输入文件的引用

[英]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. 我添加了一个部署后脚本,在其中调用了Postcode.sql脚本,该脚本将邮政编码插入到我们的一个表中。 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." 一切正常,除了当我想将CSV文件指定为批量插入的输入时,无论我做什么,我总是得到“系统找不到指定的路径”。 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: 这是Postcode.sql中的(当前测试中)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. 我将其从更改为“ FROM'c:\\ TFS \\ Project \\ InputFiles \\ Postcodes.csv'”以使其正常运行,但是我在这里需要一个路径,该路径也可以在其他开发人员的计算机上使用,因为我确定他们使用用于存储解决方案的不同文件夹。

So the question is: what is the proper format - if there are any - of pointing to that Postcodes.csv in an sql script file? 所以问题是:在SQL脚本文件中指向该Postcodes.csv的正确格式(如果有)是什么?

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): 好吧,我决定不使用sql脚本文件,而是立即从这样的部署脚本中运行命令(我使插入脚本变得更好,更短):

-- 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. 为了能够运行此程序,我必须指定一个名为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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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