Sql Case Statement when is not null

sqlsql-serversql-server-2005sql-server-2008

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

Best Solution

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'