首页 > 解决方案 > 使用 powershell 更改 SQL Server 的实例级别排序规则

问题描述

我想使用 powershell 脚本以编程方式更改 SQL Server 实例的排序规则。以下是手动步骤:

  1. 停止 SQL Server 实例
  2. 转到目录位置:“C:\Program Files\Microsoft SQL Server\MSSQL14.SQL2017\MSSQL\Binn”
  3. 执行以下命令:sqlservr -c -m -T4022 -T3659 -s"SQL2017" -q"SQL_Latin1_General_CP1_CI_AS"
  4. 执行上述命令后,显示以下消息:“默认排序规则已成功更改。”
  5. 然后我需要按 ctrl+c 停止进一步执行。如何以编程方式执行此操作?

标签: sql-serverpowershellcollation

解决方案


当我们执行命令来更改 SQL Server 排序规则时,它会在事件查看器应用程序日志中记录执行详细信息。使用循环,我们可以连续检查 SqlServr.exe 的事件查看器应用程序日志,当它生成以下日志消息:“默认排序规则已成功更改”时,我们可以终止该进程。

#Take the time stamp before execution of Collation Change Command
$StartDateTime=(Get-Date).AddMinutes(-1)

# Execute the Collation Change Process
Write-Host "Executing SQL Server Collation Change Command"
$CollationChangeProcess=Start-Process -FilePath $SQLRootDirectory -ArgumentList 
"-c -m -T 4022 -T 3659 -s $JustServerInstanceName -q $NewCollationName" - 
NoNewWindow -passthru

Do
{
  $log=Get-WinEvent -FilterHashtable @{logname='application'; 
  providername=$SQLServiceName; starttime = $StartDateTime} | Where-Object - 
  Property Message -Match 'The default collation was successfully changed.'
  IF($log.count -gt 0 -and  $log.TimeCreated -gt $StartDateTime )
  {
    Stop-Process -ID $CollationChangeProcess.ID
    write-host 'Collation Change Process Completed Successfully.'
    break
  }
  $DateTimeNow=(Get-Date)
  $Duration=$DateTimeNow-$StartDateTime
  write-host  $Duration.totalminutes
  Start-Sleep -Seconds 2
  IF ($Duration.totalminutes -gt 2)
  {
    write-host 'Collation Change Process Failed.'
    break
  }
 }while (1 -eq 1)

推荐阅读