我的 MS SQL 2008 R2 设置上有一个存储过程。该过程动态地创建一个表并向其添加索引。下面显示的是脚本的精简版,向您展示我在做什么。当我尝试将索引信息添加到“@SQL1”时,字符串长度变得太大,这就是为什么它被分成两个字符串(@SQL1 和@SQL2)。我遇到的问题是,当表不存在时一切都很好,但是当表确实存在时,脚本的索引部分仍在运行。这会失败,因为索引已经存在。记住我不能将所有脚本文本放入单个字符串中,解决此问题的最佳方法是什么?
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)