T-SQL在存储过程中检查IF NOT EXISTS列

时间:2013-01-28 09:15:39

标签: sql tsql stored-procedures sql-server-2008-r2

我对IF NOT EXISTS声明有疑问。我在使用存储过程时使用了以下代码:

IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
                         WHERE TABLE_NAME = 'tableName'
                         AND COLUMN_NAME = @fieldName
                         AND TABLE_SCHEMA = 'dbo')   
BEGIN  
       DECLARE @paramDefinitions NVARCHAR(1000)

    SET @paramDefinitions=
     '@dataType nvarchar(100) OUTPUT'
        SET @typeQuery = 'SELECT @dataType =
                  CASE 
                  WHEN s.name = ''nvarchar'' THEN ''nvarchar('' + CAST(c.max_length AS varchar(4)) + '')'' 
                      WHEN s.name = ''varchar'' THEN ''varchar('' + CAST(c.max_length AS varchar(4)) + '')''
                      WHEN s.name = ''char'' THEN ''char('' + CAST(c.max_length AS varchar(4)) + '')''
              WHEN s.name = ''nchar'' THEN ''nchar('' + CAST(c.max_length AS varchar(4)) + '')''
             ELSE s.name 
              END                 
            FROM sys.views t JOIN sys.columns c ON t.object_id = c.object_id 
                              JOIN sys.types s ON c.user_type_id = s.user_type_id 
            WHERE t.name = ''tablename'' AND c.name =' + @tmpField

            EXEC sp_executesql @typeQuery, @paramDefinitions, @dataType OUTPUT

            SET @updateTable = 'Alter table dbo.tablename add ' + @field +' '+ @dataType 
            print @updateTable

        EXEC sp_executesql @updateTable  
END

如果我现在启动SP,它会尝试重新创建已存在的列,但它也会创建任何新列。如果我将其更改为IF EXISTS,它将无法执行任何操作。

如果我自己运行select语句,那么如果列存在则得到1,如果不存在,则得到任何结果。我的错误在哪里?是否无法将IF NOT EXISTS用于此目的?

1 个答案:

答案 0 :(得分:1)

如果我想检查一个表是否包含某个列,我使用 COLUMNPROPERTY

IF COLUMNPROPERTY(object_id('[dbo].[TABLE]'), 'COLUMN_NAME', 'AllowsNull') is NULL
BEGIN
SELECT 'The column does not exists'
END