当所有数据都为空时我们如何删除列

时间:2015-04-07 04:06:52

标签: sql sql-server sql-server-2008 tsql

我在SQL Sever 2008 R2中遇到问题... 我有一个数据透视表,行是动态创建的 例如,在

中执行时

第1行

ID,Modify_Date,Line_Code,T1,T2,T6,T9,T22,T11


第2行 ID,Modify_Date,Line_Code,T4,T2,T5,T3


因此执行时有不同的结果,列中的某些字段为空,并且没有所有行的数据

enter image description here 我想删除Column" T9" 感谢

2 个答案:

答案 0 :(得分:2)

您可以参考此SQL: Select columns with NULL values only 并重写@cmd,如下所示:

SET NOCOUNT ON;

DECLARE
 @ColumnName sysname
,@DataType nvarchar(128)
,@cmd nvarchar(max)
,@TableSchema nvarchar(128) = 'dbo'
,@TableName sysname = 'TableName';--Your Table Name

DECLARE getinfo CURSOR FOR
SELECT
     c.COLUMN_NAME
    ,c.DATA_TYPE
FROM
    INFORMATION_SCHEMA.COLUMNS AS c
WHERE
    c.TABLE_SCHEMA = @TableSchema
    AND c.TABLE_NAME = @TableName;

OPEN getinfo;

FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @cmd = N'IF NOT EXISTS (SELECT * FROM ' + @TableSchema + N'.' + @TableName 
             + N' WHERE [' + @ColumnName + N'] IS NOT NULL) '
             + N' ALTER TABLE ' + @TableName + N' DROP COLUMN ' + @ColumnName + N';';
    EXECUTE (@cmd);
    FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;
END;

CLOSE getinfo;
DEALLOCATE getinfo;

答案 1 :(得分:0)

尝试此优化代码

SET NOCOUNT ON;

DECLARE @ColumnName  SYSNAME,
        @DataType    NVARCHAR(128),
        @cmd         NVARCHAR(max),
        @TableSchema NVARCHAR(128) = 'dbo',
        @TableName   SYSNAME = 'TEST'; --Your Table Name
DECLARE getinfo CURSOR FOR
  SELECT c.COLUMN_NAME,
         c.DATA_TYPE
  FROM   INFORMATION_SCHEMA.COLUMNS AS c
  WHERE  c.TABLE_SCHEMA = @TableSchema
         AND c.TABLE_NAME = @TableName
         AND C.IS_NULLABLE = 'YES'

OPEN getinfo;

FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;

WHILE @@FETCH_STATUS = 0
  BEGIN
      SET @cmd = N'IF NOT EXISTS (SELECT * FROM '
                 + @TableSchema + N'.' + @TableName + N' WHERE ['
                 + @ColumnName + N'] IS NOT NULL) '
                 + N' ALTER TABLE ' + @TableName
                 + N' DROP COLUMN ' + @ColumnName + N';';

      EXECUTE (@cmd);

      FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;
  END;

CLOSE getinfo;

DEALLOCATE getinfo;