I have a Stored Procedure on my MS SQL 2008 R2 setup. The procedure dynamically creates a table and adds indexes to it. Shown below is a cut down version of the script to show you what I am doing. When I tried adding the index information to “@SQL1” the string length became too large which is why it is split into two strings (@SQL1 And @SQL2). The problem I have is that when the table doesn’t exist all is fine but when the table does exist the Index part of the script is still run. This fails as the indexes already exist. What would be the best way to fix this remembering that I can’t put all the script text into a single string?
ALTER PROCEDURE [evt].[CreateReportingDestinationTable]
(
@Name nvarchar(50)
)
AS
SET NOCOUNT ON;
DECLARE @SQL1 nvarchar(max)
DECLARE @SQL2 nvarchar(max)
SET @SQL1 = "IF NOT EXISTS (SELECT * FROM sys.Tables WHERE name = '" + @Name + "' AND type in (N'U'))
CREATE TABLE [logs].[" + @Name + "](
[MessageId] [uniqueidentifier] NOT NULL,
[TokenNumber] [nvarchar](50) NULL,
CONSTRAINT [PK_" + @Name + "] PRIMARY KEY CLUSTERED
(
[MessageId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]"
SET @SQL2 = "CREATE NONCLUSTERED INDEX [IX_" + @Name + "_TokenNumber_EventTime] ON [logs].[" + @Name + "]
(
[TokenNumber] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
"
EXEC(@SQL1 + @SQL2)
Include the creation of the indexes in the same IF branch as the creation of the table: