Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / IBM DB2, WebSphere, IMS, U2 [игнор отключен] [закрыт для гостей] / Вычисляемое поле / 6 сообщений из 6, страница 1 из 1
10.12.2013, 22:01
    #38496252
lans
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Вычисляемое поле
Помогите решить проблему. Создаю вычисляемое поле

Код: sql
1.
2.
 ALTER TABLE DBO.TEST  ADD ISDELETED SMALLINT  
 GENERATED ALWAYS AS (COALESCE(case when  ENDDATE > DBO.GETDATE() AND BEGINDATE < DBO.GETDATE() then 0 else 1 end)) ; 


где GETDATE() функция возвращающая текущую дату. Скрипт не выполняется( вылетает ошибка

A check constraint or generated column that is defined with "GETDATE" is invalid.. SQLCODE=-548, SQLSTATE=42621, DRIVER=4.13.111

Может кто сталкивался? Заранее благодарен
...
Рейтинг: 0 / 0
10.12.2013, 22:29
    #38496271
Hunterik
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Вычисляемое поле
CURRENT_DATE ?
...
Рейтинг: 0 / 0
10.12.2013, 23:13
    #38496289
lans
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Вычисляемое поле
Тоже самое( Причём изначально так и было CURRENT_DATE , сделал функцию думал в этом проблема но как оказалось нет
...
Рейтинг: 0 / 0
11.12.2013, 07:52
    #38496410
Mark Barinstein
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Вычисляемое поле
lans,

>db2 "? sql548"


SQL0548N A check constraint or generated column that is defined with
"<check-condition-element>" is invalid.

Explanation:

A check constraint in the CREATE TABLE or CREATE NICKNAME, ALTER TABLE
or ALTER NICKNAME statement is invalid for one or more of the following
reasons:

* the constraint definition contains a subquery
* the constraint definition contains a column function
* the constraint definition contains a host variable
* the constraint definition contains a parameter marker
* the constraint definition contains a special register or a built-in
function that depends on the value of a special register
* the constraint definition contains a global variable
* the constraint definition contains a function that is not
deterministic
* the constraint definition contains a user defined function with
external action
* the constraint definition contains a user defined function with the
scratchpad option
* the definition contains a user defined function with the CONTAINS SQL
or READS SQL DATA option
* the definition contains a reference to a generated column which is
based on an expression
* the check constraint is part of a column definition, and its
check-condition contains a reference to a column name other than the
column being defined
* the generated column definition contains a reference to itself
* the constraint definition contains a dereference operation or a DEREF
function where the scoped reference argument is other than the object
identifier (OID) column.
* the constraint definition uses a TYPE predicate.
* the constraint definition includes a CAST specification with a SCOPE
clause.
* the constraint or generated column definition contains a text search
function.
* the constraint definition contains an XML column.
* the constraint definition contains an XMLQUERY or XMLEXISTS
expression.

The token within the text of the error message lists the invalid item.

The statement cannot be processed.

User response:

The user response is one of the following, depending on the cause of the
error:

* change the check constraint or generated column so that it does not
include the listed item.
* move the check constraint definition outside the column definition,
so that it becomes a table level constraint definition.
Обратите внимание на требования к функциям и запрет на использование special registries.
Интересно здесь то, что на самом деле функции с CONTAINS SQL использовать можно, но в доке почему-то указывается, что нельзя.
Вы можете попробовать создать DETERMINISTIC, NO EXTERNAL ACTION, [NO|CONTAINS SQL] функцию DBO.GETDATE(), которая будет возвращать текущую дату.

Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
create or replace function dbo.getdate()
returns date
contains sql
deterministic
no external action
return date(timestamp(generate_unique()));

create table dbo.test(
  begindate date
, enddate date
, isdeleted int
GENERATED ALWAYS AS (COALESCE(case when  ENDDATE > DBO.GETDATE() AND BEGINDATE < DBO.GETDATE() then 0 else 1 end, -1))
);
...
Рейтинг: 0 / 0
11.12.2013, 20:11
    #38497680
lans
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Вычисляемое поле
Спасибо.
...
Рейтинг: 0 / 0
12.12.2013, 02:40
    #38497851
CawaSPb
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Вычисляемое поле
lans,

Дополнение.

Я бырекомендовал поостеречься от ф-й, меняющихся со временем в GENERATED полях.
Сегодня результат один, завтра другой. Сделали EXPORT/LOAD или поигрались с INTEGRITY, а оно или перегенерилось всё, или больше текущему выражению не соответствует (и включение "SET INTEGRITY FOR ... IMMEDIATE CHECKED" больше не проходит).

Вариант с извлечением даты из GENERATE_UNIQUE() работает, но тут мы обманываем базу, т.к. ф-я, конечно, получается не DETERMINISTIC.

Луше добавить дополнительное поле NOT NULL WITH DEFAULT CURRENT DATE + выражение от него, или просто триггера before insert/before update на таблицу навесить.
...
Рейтинг: 0 / 0
Форумы / IBM DB2, WebSphere, IMS, U2 [игнор отключен] [закрыт для гостей] / Вычисляемое поле / 6 сообщений из 6, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]