简体   繁体   中英

Sql Case Statement when is not null

I want to generate declaration of variables dynamically depending on the table. I mean, I want to declare variables of a table, each variable must be the same type as its column I'm doing something like that but the result only works if the type is not an int

Select 'Declare @Doc' + COLUMN_NAME + ' '+DATA_TYPE+case(CHARACTER_MAXIMUM_LENGTH) when Null then ' '  else '(' +convert(varchar(12),CHARACTER_MAXIMUM_LENGTH) + ')' end 
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'Documentos'

And my result is this

(No column name)
NULL
Declare @DocSerie varchar(5)
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
Declare @DocImporteLetras varchar(255)
Declare @DocMotivos text(2147483647)
NULL
Declare @DocDocumentosReferencia varchar(255)
NULL
NULL
Declare @DocAuditoriaIPC varchar(40)
NULL
NULL
Declare @DocAuditoriaIPM varchar(40)
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL

CASE x WHEN null THEN is the same as CASE WHEN x = null THEN . But nothing equals null in that way. This means that you are always getting the ELSE part of your CASE statement. And that means that you are trying to concatenate a string with NULL, which always yields NULL.

You need CASE WHEN x IS NULL THEN instead...

SELECT
  'Declare @Doc'
  + COLUMN_NAME + ' '
  + DATA_TYPE
  + CASE WHEN (CHARACTER_MAXIMUM_LENGTH) IS Null then ' '  else '(' convert(varchar(12),CHARACTER_MAXIMUM_LENGTH) + ')' end 
FROM
  INFORMATION_SCHEMA.COLUMNS 
WHERE
  TABLE_NAME = 'Documentos'

Coalesce

SELECT 'Declare @Doc'
  + COLUMN_NAME + ' '
  + DATA_TYPE + Coalesce('(' + CHARACTER_MAXIMUM_LENGTH + ')', '')
FROM
  INFORMATION_SCHEMA.COLUMNS 
WHERE
  TABLE_NAME = 'Documentos'

Switch Case

SELECT 'Declare @Doc' 
  + COLUMN_NAME + ' ' 
  + DATA_TYPE 
  + Case When CHARACTER_MAXIMUM_LENGTH Is Null Then '' Else '(' + Convert(Varchar, CHARACTER_MAXIMUM_LENGTH) + ')' End
FROM
  INFORMATION_SCHEMA.COLUMNS 
WHERE
  TABLE_NAME = 'Documentos'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM