A DB2 null Indicator/value represents missing or unknown information at the column level.
When a column is set as null, it can mean one of two things:
the attribute is not applicable for certain occurrences of the entity, or the attribute applies to all entity occurrences, but the information may not
always be known.
It could be a combination of these two situations too.
A DB2 null Indicator/value is not the same as Zero or blank.
For all Columns that can contain Nulls, indicator variable should be used in all Select Statements to retrieve data -or- the COALESCE built-in function
should be used.
|
Um indicador/valor nulo do DB2 representa informações ausentes ou desconhecidas no nível da coluna.
Quando uma coluna é definida como nula, isso pode significar uma das duas coisas:
o atributo não é aplicável para certas ocorrências da entidade ou o atributo se aplica a todas as ocorrências da entidade, mas as informações podem nem
sempre ser conhecidas.
Pode ser uma combinação dessas duas situações também.
Um Indicador/valor nulo do DB2 não é igual a Zero ou em branco.
Para todas as colunas que podem conter nulos, a variável indicadora deve ser usada em todas as instruções de seleção para recuperar dados -ou- a função
embutida COALESCE deve ser usada.
|
Syntax:
The PICTURE clause that should be used for the DB2 null indicator is PIC S9(4) COMP.
A cláusula PICURE que deve ser usada para o indicador nulo do DB2 é PIC S9 (4) COMP.
Meaning:
- 0 : the field is not null
- -1 : the field is null
- -2 : the field value is truncated
Inserting a record with a nullable column:
- To insert a NULL, move -1 to the null indicator
- To insert a valid value, move 0 to the null indicator
Every column defined to a DB2 table must be designated as either allowing or disallowing nulls.
A column is defined as nullable – meaning it can be set to NULL – in the table creation DDL.
Null is the default if nothing is specified after the column name.
To prohibit the column from being set to NULL you must explicitly specify NOT NULL after the column name.
In the following sample table, COL1 and COL3 can be set to null, but not COL2, COL4, or COL5:
|
Significado:
- 0 : o campo não é nulo
- -1 : o campo é nulo
- -2 : o valor do campo é truncado
Inserindo um registro com uma coluna anulável:
- Para inserir um NULL, mova -1 para o indicador nulo
- Para inserir um valor válido, mova 0 para o indicador nulo
Cada coluna definida para uma tabela do DB2 deve ser designada como permitindo ou proibindo nulos.
Uma coluna é definida como anulável - o que significa que pode ser definida como NULL - na DDL de criação da tabela.
Nulo é o padrão se nada for especificado após o nome da coluna.
Para proibir que a coluna seja definida como NULL, você deve especificar explicitamente NOT NULL após o nome da coluna.
Na tabela de amostra a seguir, COL1 e COL3 podem ser definidos como nulos, mas não COL2, COL4 ou COL5:
|
Table Declaration:
CREATE TABLE SAMPLE
(COL1 INTEGER,
COL2 CHAR(10) NOT NULL,
COL3 CHAR(5),
COL4 DATE NOT NULL WITH DEFAULT,
COL5 TIME NOT NULL);
|
Select Query:
EXEC SQL
SELECT TQ_UOWPRR_DESC
, TQ_UOWPRIOR_ID
, TQ_PRRACTVTY_DT
, TQ_MIGRATION_DT
, TQ_DELETION_IND
INTO
TQ_UOWPRR_DESC :IND-UOWPRR-DESC
, TQ_UOWPRIOR_ID :IND-UOWPRIOR-ID
, TQ_PRRACTVTY_DT :IND-PRRACTVTY-DT
, TQ_MIGRATION_DT :IND-MIGRATION-DT
, TQ_DELETION_IND :IND-DELETION1IND
FROM TQ1
WHERE TSQRY_PRODSGMT_CD = :TSQRY-PRODSGMT-CD
AND TSQRY_CLNTSGMT_CD = :TSQRY-CLNTSGMT-CD
AND TQ_REC_ID = :TQ-REC-ID
AND TQ_TPPREFIX_CD = :TQ-TPPREFIX-CD
END-EXEC.
|
Declare cursor:
EXEC SQL
DECLARE TQ_CSR CURSOR FOR
SELECT TQ_UOWPRR_DESC
, TQ_UOWPRIOR_ID
, TQ_PRRACTVTY_DT
, TQ_MIGRATION_DT
, TQ_DELETION_IND
FROM TQ1
WHERE TSQRY_PRODSGMT_CD = :TSQRY-PRODSGMT-CD
AND TSQRY_CLNTSGMT_CD = :TSQRY-CLNTSGMT-CD
AND TQ_REC_ID = :TQ-REC-ID
AND TQ_TPPREFIX_CD = :TQ-TPPREFIX-CD
END-EXEC.
|
Fetch Cursor:
EXEC SQL
FETCH TQ_CSR
INTO :TQ-UOWPRR-DESC :IND-UOWPRR-DESC
, :TQ-UOWPRIOR-ID :IND-UOWPRIOR-ID
, :TQ-PRRACTVTY-DT :IND-PRRACTVTY-DT
, :TQ-MIGRATION-DT :IND-MIGRATION-DT
, :TQ-DELETION-IND :IND-DELETION-IND
END-EXEC.
|
Rowset:
EXEC SQL
FETCH NEXT TQ_CSR
FOR 10 ROWS
INTO :TQ-UOWPRR-DESC :IND-UOWPRR-DESC
, :TQ-UOWPRIOR-ID :IND-UOWPRIOR-ID
, :TQ-PRRACTVTY-DT :IND-PRRACTVTY-DT
, :TQ-MIGRATION-DT :IND-MIGRATION-DT
, :TQ-DELETION-IND :IND-DELETION-IND
END-EXEC.
|
The purposes of the indicator variable are to:
- Specify the null value.
A negative value of the indicator variable specifies the null value.
A value of -2 indicates a numeric conversion or arithmetic expression error occurred in deriving the result
- Record the original length of a truncated string (if the source of the value is not a large object type)
- Record the seconds’ portion of time if the time is truncated on assignment to a host variable.
|
Os objetivos da variável indicadora são:
- Especifique o valor nulo.
Um valor negativo da variável do indicador especifica o valor nulo.
Um valor de -2 indica que ocorreu uma conversão numérica ou erro de expressão aritmética ao derivar o resultado
- Registre o comprimento original de uma string truncada (se a fonte do valor não for um tipo de objeto grande)
- Registre a parte dos segundos de tempo se o tempo for truncado na atribuição a uma variável de host.
|
For example, if :TQ-UOWPRR-DESC: IND-UOWPRR-DESC is used to specify an insert or update value, and if IND-UOWPRR-DESC is negative, the value
specified is the null value. If IND-UOWPRR-DESC is not negative the value specified is the value of TQ-UOWPRR-DESC.
Similarly, if :TQ-UOWPRR-DESC: IND-UOWPRR-DESC is specified in a VALUES INTO clause or in a FETCH or SELECT INTO statement, and if the value
returned is null, TQ-UOWPRR-DESC is not changed and IND-UOWPRR-DESC is set to a negative value.
If the value returned is not null, that value is assigned to TQ-UOWPRR-DESC and IND-UOWPRR-DESC is set to zero (unless the assignment to TQ-UOWPRR-DESC
requires string truncation of a non-LOB string; in which case IND-UOWPRR-DESC is set to the original length of the string).
If an assignment requires truncation of the seconds part of time, IND-UOWPRR-DESC is set to the number of seconds.
|
Por exemplo , se: TQ-UOWPRR-DESC: IND-UOWPRR-DESC for usado para especificar um valor de inserção ou atualização, e se IND-UOWPRR-DESC for negativo,
o valor especificado é o valor nulo.
Se IND-UOWPRR-DESC não for negativo, o valor especificado é o valor de TQ-UOWPRR-DESC.
Da mesma forma , se: TQ-UOWPRR-DESC: IND-UOWPRR-DESC for especificado em uma cláusula VALUES INTO ou em uma instrução FETCH ou SELECT INTO, e se o
valor retornado for nulo, TQ-UOWPRR-DESC não será alterado e IND- UOWPRR-DESC é definido com um valor negativo.
Se o valor retornado não for nulo, esse valor será atribuído a TQ-UOWPRR-DESC e IND-UOWPRR-DESC será definido como zero (a menos que a atribuição a
TQ-UOWPRR-DESC exija o truncamento de string de uma string não LOB; em que case IND-UOWPRR-DESC é definido com o comprimento original da string).
Se uma atribuição exigir o truncamento da parte do tempo dos segundos, IND-UOWPRR-DESC é definido com o número de segundos.
|
SQL Code -305
- If the table column is defined as NOT NULL (with no default) and if we try to insert a null value we get this error.
Resoulution: This should be resolved by making sure that the inserted value is not null. DB2 Null indicator cannot be used here since the column
is defined as NOT NULL.
(validate the data, if it’s not numeric or less than spaces then move spaces into it and then insert or update into table)
- A table column is defined as NULL, The host variable has a not null value and the DB2 Null indicator is not set in the host program, so the null
indicator defaults to a negative value.
Resoulution: This should be resolved by using a null indicator in the host program and moving the relevant value to the null indicator.
Here in order to move the null value into the respective column move -1 to null indicator.
|
Código SQL -305
- Se a coluna da tabela for definida como NOT NULL (sem padrão) e se tentarmos inserir um valor nulo, obteremos este erro.
Resolução: Isso deve ser resolvido certificando-se de que o valor inserido não seja nulo. O indicador DB2 Null não pode ser usado aqui, pois a
coluna está definida como NOT NULL.
(valide os dados, se não forem numéricos ou forem menores que espaços, mova os espaços para eles e insira ou atualize na tabela)
- Uma coluna da tabela é definida como NULL. A variável do host tem um valor não nulo e o indicador DB2 Null não está definido no programa do host,
portanto, o padrão do indicador nulo é um valor negativo.
Resolução: Isso deve ser resolvido usando um indicador nulo no programa host e movendo o valor relevante para o indicador nulo.
Aqui, a fim de mover o valor nulo para a respectiva coluna, mova -1 para o indicador nulo.
|
Points to consider:
- NULLs can present problems because it is handled differently by different computers and the collating sequence is inconsistent with
regard to NULLs.
- Unless you specify NOT NULL, the default is to allow for NULLs
- It’s easy for us to get lazy and allow columns to contain NULLs when it would be better to specify NOT NULL
- Remember to allow for NULLs creating UNKNOWN logical values.
Always test your code with NULLs in all possible places.
- The NULL is a global creature, not belonging to any particular data type, but able to replace any of their values.
- The basic rule for math with NULLs is that they propagate.
An arithmetic operation with a NULL will return a NULL.
If you have a NULL in an expression, the result will be NULL.
- If you concatenate a zero length string to another string, that string stays the same.
If you concatenate a NULL string to a string, the string becomes a NULL.
- In comparisons, the results can be TRUE, FALSE, or UNKNOWN.
A NULL in a row will give an UNKNOWN result in the comparison.
- Sometimes negating the wording of the problem helps.
Instead of saying “Give me the cars that met all the test criteria,” say “Don’t give me any car that failed one of the test criteria.”
It is often easier to find what you do not want than what you do want.
This is very true when you use the NOT EXISTS, but beware of NULLs and empty tables when you try this.
- You can’t completely avoid NULLs in SQL.
However, it is a good idea to try as hard as you can to avoid them whenever possible.
- Make yourself think about whether you really need NULLs to exist in a column before you omit the NOT NULL clause on the column
definition.
|
Pontos a considerar:
- NULLs podem apresentar problemas porque são tratados de maneira diferente por computadores diferentes e a seqüência de agrupamento é inconsistente em
relação aos NULLs.
- A menos que você especifique NOT NULL, o padrão é permitir NULLs
- É fácil para nós ficar preguiçosos e permitir que as colunas contenham NULLs quando seria melhor especificar NOT NULL
- Lembre-se de permitir NULLs criando valores lógicos DESCONHECIDOS.
Sempre teste seu código com NULLs em todos os lugares possíveis.
- O NULL é uma criatura global, não pertencente a nenhum tipo de dado em particular, mas capaz de substituir qualquer um de seus valores.
- A regra básica para matemática com NULLs é que eles se propagam.
Uma operação aritmética com um NULL retornará um NULL.
Se você tiver um NULL em uma expressão, o resultado será NULL.
- Se você concatenar uma string de comprimento zero com outra string, essa string permanecerá a mesma.
Se você concatenar uma string NULL em uma string, a string se tornará um NULL.
- Em comparações, os resultados podem ser TRUE, FALSE ou UNKNOWN.
Um NULL em uma linha dará um resultado DESCONHECIDO na comparação.
- Às vezes, negar a formulação do problema ajuda.
Em vez de dizer "Dê-me os carros que atenderam a todos os critérios de teste", diga "Não me dê nenhum carro que falhou em um dos critérios de teste".
Freqüentemente, é mais fácil encontrar o que você não deseja do que o que deseja.
Isso é muito verdadeiro quando você usa NOT EXISTS, mas tome cuidado com os NULLs e as tabelas vazias ao tentar isso.
- Você não pode evitar completamente os NULLs no SQL.
No entanto, é uma boa ideia tentar ao máximo evitá-los sempre que possível.
- Pense se você realmente precisa da existência de NULLs em uma coluna antes de omitir a cláusula NOT NULL na definição da coluna.
|
|