如何在 VS 2012 中的 SQL Server 数据库项目中存储静态数据 [英] How do you store static data in your SQL Server Database Project in VS 2012

查看:23
本文介绍了如何在 VS 2012 中的 SQL Server 数据库项目中存储静态数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 SQL Server 数据库项目来保存我们所有的表、存储过程、视图等脚本.我现在想要一种能够保留所有参考(静态)数据的方法.当工具或项目运行时,它会安装所有的 DB 对象并插入所有的引用数据.

I am trying to use the SQL Server Database Project to keep all our table, stored procedure, views etc scripts. I now want a way to be able to keep all our reference (static) data as well. When the tool or project is run it will install all the DB objects and the insert all the reference data.

我在 vs 2010 中找到了类似的文章,但他们使用了诸如面向数据库专业人员的 Team Edition 之类的东西.

I found similar articles for vs 2010 but they were using things like Team Edition for Database professionals.

  • 让我们的数据库处于源代码控制之下.
  • 将我们的本地开发数据库与源代码管理中的最新版本同步.
  • 使用 Visual Studio 2012 和 SQL Server 2012
  • 尽可能使用 .Net 工具,而不是 Redgate 之类的工具(Redgate 很棒,但如果我可以在 VS 2012 中使用工具,我还不想放弃它)

推荐答案

您可以使用这种方法:

  • 将您的参考数据放入 XML 文件中,每个表一个
  • 将带有参考数据的 XML 文件添加到您的数据库项目
  • 使用部署后脚本从 XML 中提取数据并将其合并到您的表中

这里是每个步骤的更详细说明,并附有示例.假设您需要初始化一个具有以下结构的国家/地区表:

Here is a more detailed description of each step, illustrated with an example. Let's say that you need to initialize a table of countries that has this structure:

create table Country (
    CountryId uniqueidentifier NOT NULL,
    CountryCode varchar(2) NOT NULL,
    CountryName varchar(254) NOT NULL
)

在您的数据库项目下创建一个名为 ReferenceData 的新文件夹.它应该是 Schema ObjectsScripts 的同级文件夹.

Create a new folder called ReferenceData under your database project. It should be a sibling folder of the Schema Objects and Scripts.

将名为 Country.xml 的新 XML 文件添加到 ReferenceData 文件夹.按如下方式填充文件:

Add a new XML file called Country.xml to the ReferenceData folder. Populate the file as follows:

<countries>
    <country CountryCode="CA" CountryName="Canada"/>
    <country CountryCode="MX" CountryName="Mexico"/>
    <country CountryCode="US" CountryName="United States of America"/>
</countries>

找到Script.PostDeployment.sql,添加如下代码:

DECLARE @h_Country int

DECLARE @xmlCountry xml = N'
:r ....ReferenceDataCountry.xml
'

EXEC sp_xml_preparedocument @h_Country OUTPUT, @xmlCountry

MERGE Country AS target USING (
    SELECT c.CountryCode, c.CountryName
    FROM OPENXML(@h_Country, '/countries/country', 1)
    WITH (CountryCode varchar(2), CountryName varchar(254)) as c) AS source (CountryCode, CountryName)
ON (source.CountryCode = target.CountryCode)
WHEN MATCHED THEN
    UPDATE SET CountryName = source.CountryName
WHEN NOT MATCHED BY TARGET THEN
    INSERT (CountryId, CountryCode, CountryName) values (newid(), source.CountryCode, source.CountryName)
;

我仅在 VS 2008 中尝试过此解决方案,但它应该与您的开发环境无关.

I tried this solution only in VS 2008, but it should be agnostic to your development environment.

这篇关于如何在 VS 2012 中的 SQL Server 数据库项目中存储静态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆