VS 2013数据库项目 - 填充常备数据

时间:2015-12-10 11:24:56

标签: sql sql-server deployment merge

我有一些在部署后运行的合并脚本,其中一个按照以下方式设置查找表:

MERGE INTO [Languages] AS Target
USING (VALUES
   ('English','eng','en')
  ,('French','fra','fr')
) AS Source ([LanguageName],[Iso639Code],[Locale])
ON (Target.[Iso639Code] = Source.[Iso639Code])
WHEN MATCHED THEN
 UPDATE SET 
  [LanguageName] = Source.[LanguageName], 
  [Locale] = Source.[Locale],
  [UserModified] = @UpdatedBy,
  [ModifiedDateTime] = GETDATE()
WHEN NOT MATCHED BY TARGET THEN
 INSERT([LanguageName],[Iso639Code],[Locale],[UserCreate],[CreateDateTime])
 VALUES(Source.[LanguageName],Source.[Iso639Code],Source.[Locale],@UpdatedBy,GETDATE());
GO

此表有一个[int]作为主键。这个脚本效果很好。

所以我的问题是我现在有另一个脚本需要从这个表中查找主键以插入第二个表。

MERGE INTO [Countries] AS Target
USING (VALUES
   ('England')
  ,('France')
) AS Source ([CountryName])
ON (Target.[CountryName] = Source.[CountryName])
WHEN MATCHED THEN
 UPDATE SET 
  [CountryName] = Source.[CountryName], 
  [LanguageId] = (Select LanguageID from [Languages] where [LanguageName] = Source.[LanguageName]),
  [Locale] = Source.[Locale],
  [UserModified] = @UpdatedBy,
  [ModifiedDateTime] = GETDATE()
WHEN NOT MATCHED BY TARGET THEN
 INSERT([CountryName],LanguageId,[UserCreate],[CreateDateTime])
 VALUES(Source.[CountryName],(Select LanguageID from [Languages] where [LanguageName] = Source.[LanguageName]),@UpdatedBy,GETDATE());
GO

这是将两个表与部署后脚本链接起来的正确程序吗?

1 个答案:

答案 0 :(得分:0)

玩过,是的,我所展示的,正是如何做我需要的。