如何停止动态SQL运行我的所有脚本

时间:2012-09-07 09:11:39

标签: sql-server-2008 stored-procedures dynamic-sql

我的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)

2 个答案:

答案 0 :(得分:2)

您是否可以检查索引是否存在,与使用sys.indexes (Transact-SQL)

的表格相同

这样的东西
SELECT *  
FROM sys.indexes  
WHERE name='YourIndexName' AND object_id = OBJECT_ID('YourTableName')

答案 1 :(得分:1)

在创建表的同一IF分支中包括索引的创建:

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'))
    BEGIN
        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]
        "

    SET SQL3 = ...
    ...

    EXEC(@SQL1 + @SQL2 + SQL3 + ... + ' END')