I have a table with varbinary(max)
column and nvarchar(max)
column. One of them is null and the other has a value.
I would like to return the column that has the value as a varbinary(max) c开发者_开发百科olumn. So far I have tried this, that does not work:
SELECT
A =
CASE A
WHEN NULL THEN B
ELSE A
END
FROM Table
SELECT COALESCE(A, CAST(B As varbinary(max)))
UPDATE: In response to comments (thanks) and assuming B is the nvarchar(max)
column, I have moved the CAST
inside the COALESCE
Try SELECT ISNULL(A, cast(B AS varbinary(max))) FROM TABLE
Your case statement evaluates to the dreaded A = NULL
:
CASE A WHEN NULL THEN B ELSE A END
Is the same as:
CASE WHEN A = NULL then B ELSE A END
One way to fix this is to use A IS NULL
, like:
CASE WHEN A IS NULL THEN B ELSE A END
Or even simpler:
COALESCE(A,B)
Both the when
and the coalesce
will assume the data type of the first argument. To cast the result to varbinary
, you can place the varbinary
column first, or explicitly cast:
COALESCE(CAST(A AS VARBINARY(MAX)),B)
here is the full code of create table and insert value and apply my code and only retrieve not null value
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]')
精彩评论