We had a database that was growing very large in size and the database was located on the E: drive that had a 200 GB Capacity. The drive was almost 90% full and the disk was running out of disk space. We had other drives on the server where there was available disk space, so our immediate solutions was to move a few large tables from that drive to different drive.
Here is how we did it. First, we identified the large tables by using sp_spaceused to identify the space used by every table.
Next we decided to create a new filegroup with T-SQL (you can also use SSMS to create a new file group).
ALTER DATABASE SALES ADD FILEGROUP [SECONDERYDATA]
We then had to create a file to point the new Filegroup to a new drive:
ALTER DATABASE SALES ADD FILE ( NAME = XFILENAME, FILENAME = 'new path\SALES.ndf', SIZE = 1MB, MAXSIZE = 10MB, FILEGROWTH = 1MB) TO FILEGROUP [SECONDERYDATA] GO
Now the database knows that there is another filegroup that it could use for data. Remember the Server \ Database will not start to create new files in the new file group, you will have to explicitly specify it.
Now let's see how you can move an existing table that has a Cluster Index to a different filegroup. First, let's drop the Primary Key constraint with an Move to Option ( We are assuming that there is a cluster index on the PK).
ALTER TABLE [INVOICE] DROP CONSTRAINT [INVOICE_PK] WITH (MOVE TO SECONDERYDATA)
After the move, we now recreate the PK Constraint:
ALTER TABLE [INVOICE] ADD CONSTRAINT [INVOICE_PK] PRIMARY KEY CLUSTERED ( [column name] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [SECONDERYDATA]
Remember when you recreate the PK constraint on the Seconderydata filegroup, all the data in that table will automatically be moved to the Seconderydata filegroup. This will only happen in the case of a table that has a primary key constraint and has a clustered index.
The transfer time may depend on the size of the table, so please do not do this during business hours.SQL Server will generally lock the entire table.
Now all you data for that table will be moved to the new file group. Please remember to shrink the database to make the space available to the Operating System.