选择非空列

时间:2010-10-21 12:36:03

标签: sql sql-server sql-server-2008 varbinary nvarchar

我有一个包含varbinary(max)列和nvarchar(max)列的表格。其中一个是null,另一个是值。

我想将具有值的列作为varbinary(max)列返回。到目前为止,我已经尝试过这个,但这不起作用:

SELECT 
      A =  
      CASE A
         WHEN NULL THEN B
         ELSE A 
      END
FROM Table

4 个答案:

答案 0 :(得分:5)

SELECT COALESCE(A, CAST(B As varbinary(max)))

UPDATE :在回复评论(谢谢)并假设B是nvarchar(max)列时,我已将CAST移到COALESCE

答案 1 :(得分:2)

尝试SELECT ISNULL(A, cast(B AS varbinary(max))) FROM TABLE

答案 2 :(得分:1)

您的案例陈述评估为可怕的A = NULL

CASE A WHEN NULL THEN B ELSE A END

与:

相同
CASE WHEN A = NULL then B ELSE A END

解决此问题的一种方法是使用A IS NULL,例如:

CASE WHEN A IS NULL THEN B ELSE A END

甚至更简单:

COALESCE(A,B)

whencoalesce都将采用第一个参数的数据类型。要将结果转换为varbinary,您可以先放置varbinary列,也可以显式转换:

COALESCE(CAST(A AS VARBINARY(MAX)),B)

答案 3 :(得分:0)

这里是create table和insert value的完整代码,并应用我的代码并且只检索非null值

CREATE TABLE [dbo].[SUPPLIER](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [SUPPLIER_NAME] [varchar](100) NOT NULL,
    [ADDRESS] [varchar](150) NULL,
    [CREATE_DATE] [datetime] NULL,)

    INSERT INTO [MyPayrol].[dbo].[SUPPLIER]
           ([SUPPLIER_NAME]           
           ,[CREATE_DATE])
     VALUES
           ('Khaled Nabil'
           ,GETDATE())


declare @inumberofcolumn int

select @inumberofcolumn= count(*) 
from sys.columns where OBJECT_NAME(object_id) = 'supplier'

declare @nameofcolumn varchar(100)

set @nameofcolumn =''

declare @counter int

set @counter=1


declare @colname varchar(100)

declare @statment varchar(100)

declare @value varchar(100)

while @counter <=@inumberofcolumn
begin

    select @colname= COL_NAME(object_id('[dbo].[SUPPLIER]'),@counter)
    declare @data table ([value] varchar(100))

    --set @statment = 'select '+@colname+' from [dbo].[SUPPLIER]'
      insert @data exec ('SELECT top 1 '+ @colname +' from [dbo].[SUPPLIER]') 
      select @value = [value] from @data
    if @value is not  null
    begin
        if @counter = 1
        begin   
            set @nameofcolumn = @nameofcolumn + @colname
        end
        else
        begin
            set @nameofcolumn = @nameofcolumn + ','+ @colname
        end
    end
    set  @counter = @counter+1
end



execute ('select '+@nameofcolumn+' from [dbo].[SUPPLIER]')