0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShellでリストアしたデータベースのユーザーマッピングを修正する

Posted at

リストアしたデータベースのユーザーマッピングを修正する

ログインユーザーを作成してからリストアしてもユーザーマッピングが不正になってしまう。
しょうがないからリストア後にユーザマッピングを修正する。

ログインユーザーを作成する

use master
CREATE LOGIN [apuser] WITH 
    PASSWORD=N'apuser', 
    DEFAULT_DATABASE=[master], 
    DEFAULT_LANGUAGE=[日本語], 
    CHECK_EXPIRATION=OFF, 
    CHECK_POLICY=OFF
GO
ALTER LOGIN [apuser] ENABLE
GO
$newDBServerName = "NEW"
$userName = "sa"
$password = "password"
$scriptDir=Split-Path $MyInvocation.MyCommand.Path -Parent
$createLoginUserSQL = $scriptDir + "\..\SQL\createLoginUser.sql"

sqlcmd -S $newDBServerName -U $userName -P $password -i $createLoginUserSQL

ユーザーマッピングを修正する

リストアしたデータベースのユーザーとログインユーザーをマッピングしなおす。

USE TEST
EXEC sp_change_users_login 'Update_One', 'apuser', 'apuser'
GO
$newDBServerName = "NEW"
$userName = "sa"
$password = "password"
$scriptDir=Split-Path $MyInvocation.MyCommand.Path -Parent
$modifyUserMappingSQL = $scriptDir + "\..\SQL\modifyUserMapping.sql"

sqlcmd -S $newDBServerName -U $userName -P $password -i $modifyUserMappingSQL

まとめ

これでDBサーバーの構築が自動化できそうだ。。。

$newDBServerName = "NEW"
$userName = "sa"
$password = "password"
$scriptDir=Split-Path $MyInvocation.MyCommand.Path -Parent
$createLoginUserSQL = $scriptDir + "\..\SQL\createLoginUser.sql"
$modifyUserMappingSQL = $scriptDir + "\..\SQL\modifyUserMapping.sql"

# ログインユーザー作成
sqlcmd -S $newDBServerName -U $userName -P $password -i $createLoginUserSQL

# ユーザーマッピング修正
sqlcmd -S $newDBServerName -U $userName -P $password -i $modifyUserMappingSQL
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?