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

时间:2014-11-05 13:50:15

标签: sql database csv insert bulk

我们有一个解决方案,我们在其中添加了一个数据库项目。此项目创建数据库表并在发布时插入数据。我添加了一个后期部署脚本,我在其中调用Postcode.sql脚本,将脚本代码插入到我们的一个表中。一切正常,但是当我想指定一个CSV文件作为批量插入的输入时,无论我做什么,我总是得到一个"系统找不到指定的路径。"例外。 文件夹结构如下所示:

[DatabaseProject]
[InputFiles] //folder
- Postcodes.csv
[PostDeploymentScripts] //folder
- Postcode.PostDeployment.sql //this will call the Postcode.sql
- 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

我将from改为" FROM' c:\ TFS \ Project \ InputFiles \ Postcodes.csv'"使它工作,但我需要一个可以在其他开发人员的机器上工作的路径,因为我确信他们使用不同的文件夹来存储解决方案。

所以问题是:什么是正确的格式 - 如果有的话 - 在sql脚本文件中指向Postcodes.csv?

1 个答案:

答案 0 :(得分:0)

好吧,我决定不使用sql脚本文件,但是要像这样立即从部署脚本运行命令(我已经使插入脚本更好更短):

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

为了能够运行它,我必须指定一个名为PostcodesFilePath的变量。要做到这一点:

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.
相关问题