2

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,如果不存在,则结果为 1。我的错误在哪里?不能IF NOT EXISTS用于此目的吗?

4

1 回答 1

1

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

IF COLUMNPROPERTY(object_id('[dbo].[TABLE]'), 'COLUMN_NAME', 'AllowsNull') is NULL
BEGIN
SELECT 'The column does not exists'
END
于 2013-01-28T10:06:31.457 回答