I need some help with COALESCE.

Syntax: COALESCE(Col1,Col2,Col3...) which means every time I will have to write the column names inside as parameters.

My question is can we pass the column names dynamically to this function? because number of columns keeps changing in my table.

Thanks, Sid

有帮助吗?

解决方案

Ir sounds like you have a bunch of columns and you want to move the values to the left and the NULLs to the right.

You can do this by counting the number of non-NULL values before each value and then using case statements to assign values. The following shows the code for four columns:

select (case when col1_n = 1 then col1
             when col2_n = 1 then col2
             when col3_n = 1 then col3
             when col4_n = 1 then col4
        end) as col1,
       (case when col2_n = 2 then col2
             when col3_n = 2 then col3
             when col4_n = 2 then col4
        end) as col2,
       (case when col3_n = 3 then col3
             when col4_n = 3 then col4
        end) as col3,
       (case when col4_n = 4 then col4
        end) as col4
from (select t.*,
             (case when col1 is not null then 1 end) as col1_n,
             ((case when col1 is not not null then 1 else 0 end) +
              (case when col2 is not null then 1 end)
             ) as col2_n,
             ((case when col1 is not not null then 1 else 0 end) +
              (case when col2 is not null then 1 else 0 end) +
              (case when col3 is not null then 1 end)
             ) as col3_n,
             ((case when col1 is not not null then 1 else 0 end) +
              (case when col2 is not null then 1 else 0 end) +
              (case when col3 is not null then 1 else 0 end) +
              (case when col4 is not null then 1 end)
             ) as col4_n             
      from t
     ) t;

You can see this work at SQL Fiddle (here).

If you have a unique id for each for, you can also unpivot the data, use row_number() and repivot the data.

其他提示

If you don't want to write the columns names, Try can do something like this.
This will show you all the rows when all of the columns values are null except for the columns you specified (IgnoreThisColumn1 & IgnoreThisColumn2).

DECLARE @query NVARCHAR(MAX);

SELECT @query = ISNULL(@query+', ','') + [name] 
                FROM  sys.columns 
                WHERE object_id = OBJECT_ID('yourTableName') 
                AND  [name] != 'IgnoreThisColumn1' 
                AND  [name] !=  'IgnoreThisColumn2';

SET @query = N'SELECT * FROM TmpTable WHERE COALESCE('+ @query +') IS NULL';

EXECUTE(@query)

Result

Result One

If you don't want rows when all the columns are null except for the columns you specified, you can simply use IS NOT NULL instead of IS NULL

SET @query = N'SELECT * FROM TmpTable WHERE COALESCE('+ @query +') IS NOT NULL';

Result

[Result Two[2]

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top