1

以这个例子为例,这样你就可以看到 Î 要做什么。

这就是透视信息的最终表格的样子。

Create Table [#Comparative]
(
    Branch char(32),
    [2004_January] numeric (18,2),
    [2005_January] numeric (18,2),
    [2006_January] numeric (18,2),
    [2007_January] numeric (18,2),
    [2008_January] numeric (18,2),
)


INSERT INTO [#Comparative]
VALUES ('Angeles', NULL, 13550.20, 7820.50, NULL, NULL),
       ('Detroit', NULL, 13550.20, 7820.50, NULL, NULL),
       ('New York', NULL, 13550.20, 7820.50, NULL, NULL),
       ('Arizona', NULL, 13550.20, 7820.50, NULL, NULL)

Select * from [#Comparative]

我如何创建一个过程或语句来删除仅包含 NULL 值的列集,同时考虑到表上的列将随着从其他查询创建表而发生变化,该查询将每日销售信息分组总和(销售额)每月一次,具体取决于所选日期的间隔。

4

2 回答 2

1

动态创建一条 SQL 语句,然后运行该命令。此脚本从临时表中删除一组只有空值的列(在 SP 中作为参数传递)。

CREATE PROC dbo.dropColumn
@tempTableName nvarchar(100)
AS
BEGIN
  DECLARE @dml nvarchar(max) = N''
  SELECT @dml += 'IF (SELECT MIN(' + QUOTENAME(c.name) + ') FROM [dbo].' + QUOTENAME(@tempTableName) + ') IS NULL' + CHAR(13) + CHAR(10) +
                 'BEGIN' + CHAR(13) + CHAR(10) +
                 '  EXEC (''ALTER TABLE [dbo].' + QUOTENAME(@tempTableName) + ' DROP COLUMN ' + QUOTENAME(c.name) + ''')' + CHAR(13) + CHAR(10) +
                 'END' + CHAR(13) + CHAR(10)
  FROM tempdb.sys.tables t JOIN tempdb.sys.columns c ON t.object_id = c.object_id
  WHERE t.object_id = OBJECT_ID('[tempdb].[dbo].' + QUOTENAME(@tempTableName))
  --PRINT @dml

  EXEC sp_executesql @dml
END

EXEC dbo.dropColumn '#Comparative'

结果:

Branch                              2005_January    2006_January
----------------------------------------------------------------
Angeles                             13550.20        7820.50
Detroit                             13550.20        7820.50
New York                            13550.20        7820.50
Arizona                             13550.20        7820.50
于 2013-05-02T09:54:41.983 回答
0

试试这个:这是一个例子。

创建存储过程。

CREATE PROCEDURE TestSP
(
    @IsDroped BIT       
)AS
BEGIN

    declare @test int
    declare @testcount int
    set @testcount = (select COUNT(*) from mtp )

    set @test = (select distinct 1 from mtp where name is null  group by name having COUNT(*)=@testcount  )

    if @test = 1 AND @IsDroped = 1
    begin
    alter table mtp drop column name
    end

END

执行这个 SP

EXEC TestSP 1
于 2013-05-02T05:59:00.927 回答