Creating an index

This recipe shows how to create a nonclustered index with an included column using PowerShell and SMO.

Getting ready

We will use the Person.Person table in the AdventureWorks2014 database. We will create a nonclustered index on FirstName, LastName, and include MiddleName. The T-SQL equivalent of this task is as follows:

CREATE NONCLUSTERED INDEX [idxLastNameFirstName]
ON [Person].[Person]
(
  [LastName] ASC,
  [FirstName] ASC
)
INCLUDE ([MiddleName])
GO

How to do it...

Let's check out how we can create an index using PowerShell:

  1. Open PowerShell ISE as administrator.
  2. Import the SQLPS module and create a new SMO Server object:
    #import SQL Server module Import-Module SQLPS -DisableNameChecking #replace this with your instance name $instanceName ...

Get SQL Server 2014 with PowerShell v5 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.