如何在select查询中忽略声明的临时表列,其中所有字段都具有列

时间:2018-03-07 09:39:19

标签: sql sql-server tsql

我需要忽略从声明的临时表中选择查询中所有列值为空的列。

DECLARE @TempTable TABLE (
    [RowID] INT not null primary key identity(1, 1),        
    [ID] BIGINT,
    [Column1] BIGINT,
    [Column2] CHAR(10)
);

INSERT INTO @TempTable (ID, Column1, column2) VALUES (1, NULL, NULL) ;
INSERT INTO @TempTable (ID, Column1, column2) VALUES (2, NULL, NULL) ;
INSERT INTO @TempTable (ID, Column1, column2) VALUES (3, NULL, NULL) ;
INSERT INTO @TempTable (ID, Column1, column2) VALUES (4, NULL, NULL) ;

SELECT * FROM @TempTable

这里在select查询中我想忽略Column1和Column2,因为所有行的值都为null。

或者另一种说法 “如何只检索任何行中至少有一个非空值的列。”

我在下面找到了一个链接,但它没有多大帮助。

How to retreive only columns which having at least one not null value in any row.

2 个答案:

答案 0 :(得分:1)

尝试使用动态sql。根据case语句(计算空值)构建COLUMNS列表,然后将其添加到查询中    编辑:#TempTable而不是@TempTable会更好。

$first_array = [
'product 1' => ['name 1' => 'shortcut 1'],
'product 2' => ['name 2' => 'shortcut 2']
];

$second_array = [
'product 1' => ['shortcut 1' => 'text 1'],
'product 2' => ['shortcut 2' => 'text 2']
];
$new_array = array();
foreach($first_array as $key=>$value)
{
    foreach($value as $key1=>$value1)
    {
        if(isset($second_array[$key][$value1]))
        $new_array[$key][$key1]=$second_array[$key][$value1];
    }
}
print_r($new_array);

答案 1 :(得分:0)

这是一种通用方法:

DECLARE @TableName VARCHAR(100) = '#YourTableName'

IF OBJECT_ID('tempdb..#ValidColumns') IS NOT NULL
    DROP TABLE #ValidColumns

CREATE TABLE #ValidColumns (ColumnName VARCHAR(100))

DECLARE @ColumnName VARCHAR(100)

DECLARE ColumnCursor CURSOR FOR
    SELECT
        QUOTENAME(C.Name)
    FROM
        tempdb.sys.columns AS C
    WHERE
        C.object_id = OBJECT_ID('tempdb..' + @TableName)

OPEN ColumnCursor
FETCH NEXT FROM ColumnCursor INTO @ColumnName

DECLARE @DynamicSQL VARCHAR(MAX)

WHILE @@FETCH_STATUS = 0
BEGIN

    SET @DynamicSQL = '
        IF EXISTS (SELECT 1 FROM ' + @TableName + ' AS T WHERE T.' + @ColumnName + ' IS NOT NULL)
        BEGIN
            INSERT INTO #ValidColumns (ColumnName) VALUES (''' + @ColumnName + ''')
        END
    '

    EXEC (@DynamicSQL)

    FETCH NEXT FROM ColumnCursor INTO @ColumnName

END

CLOSE ColumnCursor
DEALLOCATE ColumnCursor

DECLARE @SelectColumnList VARCHAR(MAX) = STUFF(
    (
        SELECT
            ',' + C.ColumnName
        FROM
            #ValidColumns AS C
        FOR XML
            PATH ('')
    ),
    1, 1, '')

SET @DynamicSQL = 'SELECT ' + @SelectColumnList + ' FROM ' + @TableName

EXEC (@DynamicSQL)

它有点乱,但它是处理具有多列的动态时态表名称的唯一方法。