powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Oracle [игнор отключен] [закрыт для гостей] / Доступ к битам поля
36 сообщений из 36, показаны все 2 страниц
Доступ к битам поля
    #32111625
babay
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Доброго времени суток!
Ситуация следующая. Некоторое поле таблицы хотелось бы использовать для настройки индивидуальных параметров просмотра/редактирования данных в приложении применительно для каждого пользователя (чтобы не создавать ключи в реестре и ini-файлы). Естесственно, нужно чтобы пользователи при этом друг другу не мешали.
Вроде бы, можно реализовать это как работу с байтами (т.е. порядковый номер символа в строке определяет пользователя). Однако если пользователей много, то в достаточно большой таблице пропадает зазря куча места.
Может быть существует вариант более изящный (например с битами)? Заранее благодарен.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32111641
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Postroi maska as RAW(n) ili LONG RAW.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32111654
new one
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
мне кажется это изврат,
лучеш по признаку их разнеси (поле - пользоваетель и нормальна работай)
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32111738
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Komanda UTL_RAW.Compare rabotaet bystree vsego!
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32111832
babay
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Прежде всего извиняюсь за молчание.

2new one:
Не подходит, а если у тебя сотни пользователей?

2Oracle X-pert:
Команды raw(n) в 8-ке нет или я чего-то не понял. А использовать для этих целей обычный number не получится? А хотелось бы именно с ним работать.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32111859
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Pogalyista::
Est' dve col a i b datatype is number
{ vspomni, oni vse hranyatsya v formate 'DOUBLE_WORLD' in comp.
ya ih sravnivau::

Declare
result Number := 0;
begin


Result := UTL_RAW.compare(
UTL_RAW.cast_to_raw(TO_CHAR(a => :a)),
UTL_RAW.cast_to_raw(TO_CHAR(b => :b)));

/* If Result = 0 --- oni identichny
Else
Nomer Bit s cotorogo nachinautsya razlichiya.*/
end;


V 8.05 UTL_RAW nado ustanavlivat' dopolnitel'no ( source mogy vyslat'..)
a v 8i/9i - standartnyi packet.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32111988
babay
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Но мне-то нужно вытащить из поля определенный бит, а не просто узнать что колонки содержат разные значения. Кроме того, кажется мне, что пример просто выдает 0 для одинаковых значений и 1 для разных.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32111994
Фотография Denis Popov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Т.е., не затрагивая структуру БД, тебе требуются битовые операции в Oracle? Есть функция BITAND:
http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/functions14a.htm#SQLRF00612

Если потребуются функции для других битовых операций, могу кинуть функции.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112019
babay
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Спасибо. Страница у меня недоступна, попробую позже.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112033
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Spec Pack UTL_RAW::

CREATE OR REPLACE PACKAGE SYS.utl_raw IS

------------
-- OVERVIEW
--
-- This package provides SQL functions for raws that concat,
-- substr, etc. to/from raws. This package is necessary
-- because normal SQL functions do not operate on raws and
-- PL/SQL does not allow overloading between a raw and a char
-- datatype. Also included are routines which convert various
-- COBOL number formats to/from raws.

-- UTL_RAW is not specific to the database environment and may
-- actually be used in other environments as it exists here.
-- For this reason, the prefix UTL has been given to the package
-- instead of DBMS.

-------
-- USES
--
-- The are many possible uses for the raw functions. The
-- functionality allows a raw "record" to be composed
-- of many elements. By using the raw datatype, character
-- set conversion will not be performed keeping the raw in
-- its original format when being transferred via rpc.
-- The raw functions also give the ability to manipulate
-- binary data which was previously limited to the hextoraw
-- and rawtohex functions.

---------------------------
-- PROCEDURES AND FUNCTIONS

/*----------------------------------------------------------------*/
/* CONCAT */
/*----------------------------------------------------------------*/
FUNCTION concat(r1 IN RAW DEFAULT NULL,
r2 IN RAW DEFAULT NULL,
r3 IN RAW DEFAULT NULL,
r4 IN RAW DEFAULT NULL,
r5 IN RAW DEFAULT NULL,
r6 IN RAW DEFAULT NULL,
r7 IN RAW DEFAULT NULL,
r8 IN RAW DEFAULT NULL,
r9 IN RAW DEFAULT NULL,
r10 IN RAW DEFAULT NULL,
r11 IN RAW DEFAULT NULL,
r12 IN RAW DEFAULT NULL) RETURN RAW;
pragma RESTRICT_REFERENCES(concat, WNDS, RNDS, WNPS, RNPS);

-- Concatenate a set of 12 raws into a single raw. If the
-- concatenated size exceeds 32K, an error is returned.

-- Input parameters:
-- r1....r12 are the raw items to concatenate.

-- Defaults and optional parameters: None

-- Return value:
-- raw - containing the items concatenated.

-- Errors:
-- VALUE_ERROR exception raised (to be revised in a future release)
-- If the sum of the lengths of the inputs exceeds the maximum
-- allowable length for a RAW.

/*----------------------------------------------------------------*/
/* CAST_TO_RAW */
/*----------------------------------------------------------------*/
FUNCTION cast_to_raw(c IN VARCHAR2 CHARACTER SET ANY_CS) RETURN RAW;
pragma RESTRICT_REFERENCES(cast_to_raw, WNDS, RNDS, WNPS, RNPS);

-- Cast a varchar2 to a raw
-- This function converts a varchar2 represented using N data bytes
-- into a raw with N data bytes.
-- The data is not modified in any way, only its datatype is recast
-- to a RAW datatype.

-- Input parameters:
-- c - varchar2 or nvarchar2 to be changed to a raw

-- Defaults and optional parameters: None

-- Return value:
-- raw - containing the same data as the input varchar2 and
-- equal byte length as the input varchar2 and without a
-- leading length field.
-- null - if c input parameter was null

-- Errors:
-- None

/*----------------------------------------------------------------*/
/* CAST_TO_VARCHAR2 */
/*----------------------------------------------------------------*/
FUNCTION cast_to_varchar2(r IN RAW) RETURN VARCHAR2;
pragma RESTRICT_REFERENCES(cast_to_varchar2, WNDS, RNDS, WNPS, RNPS);

-- Cast a raw to a varchar2
-- This function converts a raw represented using N data bytes
-- into varchar2 with N data bytes.
-- NOTE: Once the value is cast to a varchar2, string
-- operations or server->client communication will assume
-- that the string is represented using the database's
-- character set. "Garbage" results are likely if these
-- operations are applied to a string that is actually
-- represented using some other character set.

-- Input parameters:
-- r - raw (without leading length field) to be changed to a
-- varchar2)

-- Defaults and optional parameters: None

-- Return value:
-- varchar2 - containing having the same data as the input raw
-- null - if r input parameter was null

-- Errors:
-- None

/*----------------------------------------------------------------*/
/* CAST_TO_NVARCHAR2 */
/*----------------------------------------------------------------*/
FUNCTION cast_to_nvarchar2(r IN RAW) RETURN NVARCHAR2;
pragma RESTRICT_REFERENCES(cast_to_nvarchar2, WNDS, RNDS, WNPS, RNPS);

-- Cast a raw to a nvarchar2
-- This function converts a raw represented using N data bytes
-- into nvarchar2 with N data bytes.
-- NOTE: Once the value is cast to a nvarchar2, string
-- operations or server->client communication will assume
-- that the string is represented using the database's
-- NCHAR character set. "Garbage" results are likely if these
-- operations are applied to a string that is actually
-- represented using some other character set.

-- Input parameters:
-- r - raw (without leading length field) to be changed to a
-- nvarchar2)

-- Defaults and optional parameters: None

-- Return value:
-- nvarchar2 - containing having the same data as the input raw
-- null - if r input parameter was null

-- Errors:
-- None

/*----------------------------------------------------------------*/
/* LENGTH */
/*----------------------------------------------------------------*/
FUNCTION length(r IN RAW) RETURN NUMBER;
pragma RESTRICT_REFERENCES(length, WNDS, RNDS, WNPS, RNPS);

-- Return the length in bytes of a raw r.

-- Input parameters:
-- r - the raw byte stream to be measured

-- Defaults and optional parameters: None

-- Return value:
-- number - equal to the current length of the raw.

-- Errors:
-- None

/*----------------------------------------------------------------*/
/* SUBSTR */
/*----------------------------------------------------------------*/
FUNCTION substr(r IN RAW,
pos IN BINARY_INTEGER,
len IN BINARY_INTEGER DEFAULT NULL) RETURN RAW;
pragma RESTRICT_REFERENCES(substr, WNDS, RNDS, WNPS, RNPS);

-- Return a substring portion of raw r beginning at pos for len bytes.
-- If pos is positive, substr counts from the beginning of r to find
-- the first byte. If pos is negative, substr counts backwards from the
-- end of the r. The value pos cannot be 0. If len is omitted,
-- substr returns all bytes to the end of r. The value len cannot be
-- less than 1.

-- Input parameters:
-- r - the raw byte-string from which a portion is extracted.
-- pos - the byte pisition in r at which to begin extraction.
-- len - the number of bytes from pos to extract from r (optional).

-- Defaults and optional parameters:
-- len - position pos thru to the end of r

-- Return value:
-- Portion of r beginning at pos for len bytes long
-- null - if r input parameter was null

-- Errors:
-- VALUE_ERROR exception raised (to be revised in a future release)
-- when pos = 0
-- when len < 0

/*----------------------------------------------------------------*/
/* TRANSLATE */
/*----------------------------------------------------------------*/
FUNCTION translate(r IN RAW,
from_set IN RAW,
to_set IN RAW) RETURN RAW;
pragma RESTRICT_REFERENCES(translate, WNDS, RNDS, WNPS, RNPS);

-- Translate the bytes in the input r raw according to the bytes
-- in the translation raws, from_set and to_set. If a byte
-- in r has a matching byte in from_set, then it is replaced by the
-- byte in the corresponding position in to_set, or deleted.
-- Bytes in r but undefined in from_set are copied to the result.
-- Only the first (leftmost) occurrence of a byte in from_set is
-- used, subsequent duplicates are not scanned and are ignored.
-- If to_set is shorter than from_set, the extra from_set bytes
-- have no translation correspondence and any bytes in r matching
-- such uncorresponded bytes are deleted from the result raw.

-- Noted difference from TRANSLITERATE:
-- translation raws have no defaults.
-- r bytes undefined in the to_set translation raw are deleted.
-- result raw may be shorter than input r raw.

-- Input parameters:
-- r - raw source byte-string to be translated
-- from_set - raw byte-codes to be translated, if present in r
-- to_set - raw byte-codes to which corresponding from_str bytes
-- are translated

-- Defaults and optional parameters: None

-- Return value:
-- raw - translated byte-string

-- Errors:
-- VALUE_ERROR exception raised (to be revised in a future release)
-- when r is null and/or has 0 length
-- when from_set is null and/or has 0 length
-- when to_set is null and/or has 0 length

/*----------------------------------------------------------------*/
/* TRANSLITERATE */
/*----------------------------------------------------------------*/
FUNCTION transliterate(r IN RAW,
to_set IN RAW DEFAULT NULL,
from_set IN RAW DEFAULT NULL,
pad IN RAW DEFAULT NULL) RETURN RAW;
pragma RESTRICT_REFERENCES(transliterate, WNDS, RNDS, WNPS, RNPS);

-- Transliterate the bytes in the input r raw according to the bytes
-- in the transliteration raws, from_set and to_set.
-- Successive bytes in r are looked-up in the from_set and, if not
-- found, copied unaltered to the result raw, or if found, replaced
-- in the result raw by either corresponding bytes in the to_set or
-- the pad byte when no correspondence exists.
-- Bytes in r but undefined in from_set are copied to the result.
-- Only the first (leftmost) occurrence of a byte in from_set is
-- used, subsequent duplicates are not scanned and are ignored.
-- The result raw is always the same length as r.
-- from_set and to_set may be of any length.
-- If the to_set is shorter than the from_set, then the pad byte is
-- placed in the result raw when a selected from_set byte has no
-- corresponding to_set byte (as if the to_set were extended to the
-- same length as the from_set with pad bytes).

-- Noted difference from TRANSLATE:
-- r bytes undefined in to_set are padded.
-- result raw is always same length as input r raw.

-- Input parameters:
-- r - raw input byte-string to be transliterated
-- from_set - raw byte-codes to be translated ,if present in r
-- to_set - raw byte-codes to which corresponding from_set bytes
-- are translated
-- pad - 1 byte used when to-set is shorter than the from_set

-- Defaults and optional parameters:
-- from_set - x'00 through x'ff.
-- to_set - to the null string and effectively extended
-- with pad to the length of from_set as necessary.
-- pad - x'00'.

-- Return value:
-- raw - transliterated byte-string

-- Errors:
-- VALUE_ERROR exception raised (to be revised in a future release)
-- when r is null and/or has 0 length

/*----------------------------------------------------------------*/
/* OVERLAY */
/*----------------------------------------------------------------*/
FUNCTION overlay(overlay_str IN RAW,
target IN RAW,
pos IN BINARY_INTEGER DEFAULT 1,
len IN BINARY_INTEGER DEFAULT NULL,
pad IN RAW DEFAULT NULL) RETURN RAW;
pragma RESTRICT_REFERENCES(overlay, WNDS, RNDS, WNPS, RNPS);

-- Overlay the specified portion of target raw with overlay raw,
-- starting from byte position pos of target and proceding for len
-- bytes.
-- If overlay has less than len bytes, it is extended to len bytes
-- using the pad byte. If overlay exceeds len bytes, the extra
-- bytes in overlay are ignored.
-- If len bytes beginning at position pos of target exceeds the
-- length of target, target will be extended to contain the entire
-- length of overlay.
-- len, if specified, must be => 0.
-- pos, if specified, must be => 1.
-- If pos exceeeds the length of target, target will be padded with
-- pad bytes to position pos, and then target is further extended
-- with overlay bytes.

-- Input parameters:
-- overlay_str - byte-string used to overlay target
-- target - byte-string which is to be overlayed
-- pos - position in target (numbered from 1) to start overlay
-- len - the number of target bytes to overlay
-- pad - pad byte used when overlay len exceeds overlay length
-- or pos exceeds target length.

-- Defaults and optional parameters:
-- pos - 1.
-- len - to the length of overlay.
-- pad - x'00'.

-- Return value:
-- raw - The target byte_string overlayed as specified

-- Errors:
-- VALUE_ERROR exception raised (to be revised in a future release)
-- when overlay is null and/or has 0 length
-- when target is missing or undefined
-- when length of target exceeds maximum length of a raw
-- when len < 0
-- when pos < 1

/*----------------------------------------------------------------*/
/* COPIES */
/*----------------------------------------------------------------*/
FUNCTION copies(r IN RAW,
n IN NUMBER) RETURN RAW;
pragma RESTRICT_REFERENCES(copies, WNDS, RNDS, WNPS, RNPS);

-- Return n copies of r concatenated together.

-- Input parameters:
-- r - raw to be copied
-- n - number of times to copy the raw (must be positive)

-- Defaults and optional parameters: None

-- Return value:
-- The raw copied n times.

-- Errors:
-- VALUE_ERROR exception raised (to be revised in a future release)
-- r is missing, null and/or 0 length
-- n < 1
-- when length of result exceeds maximum length of a raw

/*----------------------------------------------------------------*/
/* XRANGE */
/*----------------------------------------------------------------*/
FUNCTION xrange(start_byte IN RAW DEFAULT NULL,
end_byte IN RAW DEFAULT NULL) RETURN RAW;
pragma RESTRICT_REFERENCES(xrange, WNDS, RNDS, WNPS, RNPS);

-- Returns a raw containing all valid 1-byte encodings in succession
-- beginning with the value start_byte and ending with the value
-- end_byte.
-- If start_byte is greater than end_byte, the succession of
-- result bytes begin with start_byte, wrap thru 'FF'x to '00'x,
-- and end at end_byte.
-- If specified, start_byte and end_byte must be single byte raws.

-- Input parameters:
-- start_byte - beginning byte-code value of resulting sequence
-- end_byte - ending byte-code value of resulting sequence

-- Defaults and optional parameters:
-- start_byte - x'00'
-- end_byte - x'FF'

-- Return value:
-- raw - containing succession of 1-byte hexadecimal encodings

-- Errors:
-- None

/*----------------------------------------------------------------*/
/* REVERSE */
/*----------------------------------------------------------------*/
FUNCTION reverse(r IN RAW) RETURN RAW;
pragma RESTRICT_REFERENCES(reverse, WNDS, RNDS, WNPS, RNPS);

-- Reverse a byte sequence in raw r from end to end.
-- For example, x'0102F3' would be reversed into x'F30201' and
-- 'xyz' would be reversed into 'zyx'.
-- The result length is the same as the input raw length.

-- Input parameters:
-- r - raw to reverse

-- Defaults and optional parameters: None

-- Return value:
-- raw - containing the "reverse" of r

-- Errors:
-- VALUE_ERROR exception raised (to be revised in a future release)
-- when r is null and/or has 0 length

/*----------------------------------------------------------------*/
/* COMPARE */
/*----------------------------------------------------------------*/
FUNCTION compare(r1 IN RAW,
r2 IN RAW,
pad IN RAW DEFAULT NULL) RETURN NUMBER;
pragma RESTRICT_REFERENCES(compare, WNDS, RNDS, WNPS, RNPS);

-- Compares raw r1 against raw r2. Returns 0 if r1 and r2 are
-- identical, otherwise, returns the position of the first byte
-- from r1 that does not match r2.
-- If r1 and r2 differ in length, the shorter raw is extended on
-- the right with pad if necessary.
-- right with pad if necessary. The default pad byte is x'00'.

-- Input parameters:
-- r1 - 1st raw to be compared, may be null and/or 0 length
-- r2 - 2nd raw to be compared, may be null and/or 0 length
-- pad - byte to extend whichever of r1 or r2 is shorter

-- Defaults and optional parameters:
-- pad - x'00'

-- Return value:
-- number = 0 if raw byte strings are both null or identical; or,
-- = position (numbered from 1) of first mismatched byte

-- Errors:
-- None

/*----------------------------------------------------------------*/
/* CONVERT */
/*----------------------------------------------------------------*/
FUNCTION convert(r IN RAW,
to_charset IN VARCHAR2,
from_charset IN VARCHAR2) RETURN RAW;
pragma RESTRICT_REFERENCES(convert, WNDS, RNDS, WNPS, RNPS);

-- Convert raw r from character set from_charset to character set
-- to_charset and return the resulting raw.
-- Both from_charset and to_charset must be supported character sets
-- defined to the Oracle server.

-- Input parameters:
-- r - raw byte-string to be converted.
-- to_charset - name of NLS character set to which r is converted.
-- from_charset - name of NLS character set in which r is supplied.

-- Defaults and optional parameters: None

-- Return value:
-- raw - bytestring r converted according to the specified
-- character sets.

-- Errors:
-- VALUE_ERROR exception raised (to be revised in a future release)
-- r missing, null and/or 0 length
-- from_charset or to_charset missing, null and/or 0 length
-- from_charset or to_charset names invalid or unsupported

/*----------------------------------------------------------------*/
/* BIT_AND */
/*----------------------------------------------------------------*/
FUNCTION bit_and(r1 IN RAW,
r2 IN RAW) RETURN RAW;
pragma RESTRICT_REFERENCES(bit_and, WNDS, RNDS, WNPS, RNPS);

-- Perform bitwise logical "and" of the values in raw r1 with raw r2
-- and return the "anded" result raw.
-- If r1 and r2 differ in length, the "and" operation is terminated
-- after the last byte of the shorter of the two raws, and the
-- unprocessed portion of the longer raw is appended to the partial
-- result.
-- The result length equals the longer of the two input raws.

-- Input parameters:
-- r1 - raw to "and" with r2
-- r2 - raw to "and" with r1

-- Defaults and optional parameters: None

-- Return value:
-- raw - containing the "and" of r1 and r2
-- null - if either r1 or r2 input parameter was null

-- Errors:
-- None

/*----------------------------------------------------------------*/
/* BIT_OR */
/*----------------------------------------------------------------*/
FUNCTION bit_or(r1 IN RAW,
r2 IN RAW) RETURN RAW;
pragma RESTRICT_REFERENCES(bit_or, WNDS, RNDS, WNPS, RNPS);

-- Perform bitwise logical "or" of the values in raw r1 with raw r2
-- and return the "or'd" result raw.
-- If r1 and r2 differ in length, the "or" operation is terminated
-- after the last byte of the shorter of the two raws, and the
-- unprocessed portion of the longer raw is appended to the partial
-- result.
-- The result length equals the longer of the two input raws.

-- Input parameters:
-- r1 - raw to "or" with r2
-- r2 - raw to "or" with r1

-- Defaults and optional parameters: None

-- Return value:
-- raw - containing the "or" of r1 and r2
-- null - if either r1 or r2 input parameter was null

-- Errors:
-- None

/*----------------------------------------------------------------*/
/* BIT_XOR */
/*----------------------------------------------------------------*/
FUNCTION bit_xor(r1 IN RAW,
r2 IN RAW) RETURN RAW;
pragma RESTRICT_REFERENCES(bit_xor, WNDS, RNDS, WNPS, RNPS);

-- Perform bitwise logical "exclusive or" of the values in raw r1
-- with raw r2 and return the "xor'd" result raw.
-- If r1 and r2 differ in length, the "xor" operation is terminated
-- after the last byte of the shorter of the two raws, and the
-- unprocessed portion of the longer raw is appended to the partial
-- result.
-- The result length equals the longer of the two input raws.

-- Input parameters:
-- r1 - raw to "xor" with r2
-- r2 - raw to "xor" with r1

-- Defaults and optional parameters: None

-- Return value:
-- raw - containing the "xor" of r1 and r2
-- null - if either r1 or r2 input parameter was null

-- Errors:
-- None

/*----------------------------------------------------------------*/
/* BIT_COMPLEMENT */
/*----------------------------------------------------------------*/
FUNCTION bit_complement(r IN RAW) RETURN RAW;
pragma RESTRICT_REFERENCES(bit_complement, WNDS, RNDS, WNPS, RNPS);

-- Perform bitwise logical "complement" of the values in raw r
-- and return the "complement'ed" result raw.
-- The result length equals the input raw r length.

-- Input parameters:
-- r - raw to perform "complement" operation.

-- Defaults and optional parameters: None

-- Return value:
-- raw - which is the "complement" of r1
-- null - if r input parameter was null

-- Errors:
-- None

END UTL_RAW;
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112099
Фотография MaxU
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
http://www.jlcomp.demon.co.uk/faq/bitwise.html

использование UTL_RAW в данном случае - неоправданное расходование ресурсов сервера (для преобразования типов) !

ЗЫ не совсем понятно почему Ларри & Co не удосужились реализовать "Bitwise OR" и "Bitwise XOR" ???
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112128
Фотография softy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Замечание для Oracle X-pert: не надо опубликовывать такие большие документы. Пересылайте тому кто просил его по почте или давайте ссылку на информацию
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112147
SERG1257
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Поддерживаю new one - это изврат
А если сделать таблицу
пользователь
настройки

Много пользователей много строк. Место зря не расходуется.
Или надо настройки привязать к строке. Тогда еще одно поле - id_строки в таблице.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112206
babay
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
2SERG1257
А если у тебя в схеме пара десятков таблиц по 100000 каждой и для каждой из них нужно сохранить информацию о том какой пользователь какие столбцы пометил для своей (индивидуальной) выборки?
Неверно. Не подходит.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112583
new one
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
BABY только там и делай,
как я посоветовал...
создай таблицу настроек и все будет нормальна
(я делал, все работало, правда может для других целей...)
ну у меня на сервере порядка 400 таблиц
и окола 150 пользователей юзающих их.
без проблем все решается.

а по битаем, ты просто замудохаешься
хотя может тебе так больше нравится


Ты може точно скажи что ты хочешь, и мы найдем тебе решение
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112615
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Esli DB sozdana po tehnologii DW - to metod "Master"-"Detail" ne sovsem podhodit..
Ya dymau, chto samyi optimal;nyi variant v dannom sluchae { parameter's session } - eto ispol'zovanie temporary table :
{global temporary table on commit preserve rows}, hotya eto i potrebyet uvelicheniya razmera Temporary tablespace, no ne budet zagromogdat' code.

To MaxU:
Kak pokazyvaet analyze on Oracle'kernel,
UTL_RAW rabotaet s Double_World napryamyu, bez dopolnitel'nogo preobrazovaniya...
Kogda ty delaesh
select * from my_tab where col1 = 'TEST' kernel vse ravno perevodit
tvoi parameter 'TEST' v formy Double_World. Nu i naskol'ko eto ispol'zuet resource Servera men'she, chem UTL_RAW?
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112665
Фотография MaxU
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 автор топика,

я часто использую данный подход, он себя оправдывает при небольших таблицах ( в кот. присутствует "запакованное" поле(я) ), т.к. при использовании конструкции:
Код: plaintext
bitand(ColumnName,N)
индекс по этому полю использоваться не будет...

т.е. если я правильно понял твою задачу, то я бы использовал приблизительно след. структуру -
Код: plaintext
create table Bla_Bla (id number, table_name varchar2( 50 ), user_name varchar2( 50 ), sel_col_mask number)


т.е. в таблице будет (UsersNo * TablesNo) строк...


2 Oracle X-pert,

ну давай начнем разбор полетов...
:)

моя идея была использовать функцию BITAND, ты предложил использовать UTL_RAW, т.е. ты хочешь сказать что конструкция типа:

Код: plaintext
1.
UTL_RAW.compare(UTL_RAW.cast_to_raw(TO_CHAR(A)),UTL_RAW.cast_to_raw(TO_CHAR(B)))


будет работать быстрее чем:

Код: plaintext
BITAND(A,B)


???

чего то мне слабо верится...
;)

ЗЫ при использовании/хранении битовых масок в поле типа NUMBER существует ограничение на кол-во хранимых битовых полей, при использовании RAW такого ограничения нет - с этой точки зрения я могу понять использование RAW...
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112678
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 MaxU::

BITAND ispol'zuet razlogenie cherez funkziu 2-poryadka ( tipa sigma po .. exp(-nx).
UTL_RAW ispol'ziet pryamoe schityvanie iz databloka bez preobrazovaniya...
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112695
Фотография MaxU
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 Oracle X-pert,

а как на счет реальных тестов?

ну там создаешь табличку (100000) записей и пробуешь оба подхода, выполнив предварительно:

SQL> set timing on

что-то мне подсказывает что мой вариант будет работать быстрее...
;)
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112741
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Testirovali v Oracle (UK) na tables with 10000000rows/1.8 G...
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112743
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Kstati, SEMA toge eto testirovala....
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112874
Фотография MaxU
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
а где можно взглянуть на результаты?
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112904
Фотография Denis Popov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Я не претендую на окончательность ответа, но вот что у меня получилось.

Пояснение: PIVOT- это такая pipelined-функция. Я ее использую, чтобы с гарантитей возвратить требуемое количество записей, в данном случае- 1000000.

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
dan@oraspb>; create table test (
   2       raw1 raw( 9 )
   3     , raw2 raw( 9 )
   4     , bit1 number( 18 )
   5     , bit2 number( 18 )
   6   )
   7   /

Table created.

dan@oraspb>; insert into test (
   2       raw1
   3     , raw2
   4     , bit1
   5     , bit2
   6   )
   7   values (
   8       utl_raw.cast_to_raw('111111111')
   9     , utl_raw.cast_to_raw('222222222')
  10     ,  313131313131313131 
  11     ,  323232323232323232 
  12   );

dan@oraspb>; commit;

Commit complete.

Elapsed:  00 : 00 : 00 . 00 
dan@oraspb>; 
dan@oraspb>; set autot traceonly stat
dan@oraspb>; set timing on
dan@oraspb>; 
dan@oraspb>; select bitand(bit1, bit2)
   2   from test
   3      , table(pivot( 1 ,  1000000 ))
   4   /

 1000000  rows selected.

Elapsed:  00 : 00 : 52 . 08 

dan@oraspb>; select utl_raw.bit_and(raw1, raw2)
   2   from test
   3      , table(pivot( 1 ,  1000000 ))
   4   /

 1000000  rows selected.

Elapsed:  00 : 02 : 33 . 00 


Получается 00:52.08 у BITAND() против 02:33.00 у UTL_RAW.BIT_AND().
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32112926
Фотография MaxU
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 Denis Popov,

спасибо что не поленился тест написать!
:)

2 Oracle X-pert,

я все бы еще не отказался взглянуть на результаты Oracle (UK)...
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113243
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Pervoe::
Proverka nekorrectna, t.k.:
Structure Table;:
table { col1 Number, col2 .... colN raw(100));

Syt' proverki::

select * from my_tab
where UTL_RAW.COMPARE(colN,utl_raw.cast_tow_raw('MY PARAMETER')) = 0;

a ne select bitand(bit1, bit2)...


2 MaxU. Cheloveku, rabotauchemy na Euromarket stydno ne znat' vnutrennie pravila ISO i trebovat' vnutrennie dokumenty company. Obratis' napramyu, tebe dadyt, Otchet ne zasekrechen... Ya ge etogo delat' ne imeu prava i ne budu.
Sorry,
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113490
Фотография Denis Popov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2Oracle X-pert: Собственно, тебя просят показать не "vnutrennie dokumenty company", а выкладки, на основании которых был сделан вывод, что в операциях сравнения выгоднее использовать RAW. Мне любопытно: такой вывод был сделан на основании того, что данные типа RAW ва-аще можно сравнивать, раз существует функция UTL_RAW.COMPARE()? Но во-первых, мы говорим про битовые операции, а не сравнение побитно. Если уж стоит задача в сравнении двух чисел, то я, пожалуй, воспользуюсь тем же NUMBER, и буду сравнивать через операцию "=". Во-вторых, бог с ним, давай просто сравним стоимости миллиона вызовов UTL_RAW.COMPARE() и BITAND(). Особого смысла в этом не вижу, поскольку они выполняют разные операции (иначе не существовала бы функция UTL_RAW.BIT_AND()).

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
create or replace type tbl_integer as table of integer;
/
create or replace function pivot_integer (
    p_start number
  , p_end number
) return tbl_integer
parallel_enable pipelined is
begin
  for i in p_start..p_end loop
    pipe row(i);
  end loop;
  return;
end;
/
create or replace type tbl_raw as table of raw( 9 )
/
create or replace function pivot_raw (
    p_start number
  , p_end number
) return tbl_raw
parallel_enable pipelined is
begin
  for i in p_start..p_end loop
    pipe row(utl_raw.cast_to_raw(i));
  end loop;
  return;
end;
/


Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
dan@oraspb>; set autot traceonly stat
dan@oraspb>; set timing on
dan@oraspb>; select * from table(pivot_integer( 1 ,  1000000 )) 
   2   where bitand(column_value,  123 ) =  123 
   3   /                                                                 

 15624  rows selected.

Elapsed:  00 : 00 : 05 . 06 

dan@oraspb>; select * from table(pivot_raw( 1 ,  1000000 )) 
   2   where utl_raw.compare(column_value, utl_raw.cast_to_raw( 123 )) =  0 
   3   /
                    
Elapsed:  00 : 04 : 11 . 09 


Заметь, два этих запроса отвечают на совершенно разные вопросы, "AND" и "=". Я подозреваю, что загвоздка может быть в постоянном вызове UTL_RAW.CAST_TO_RAW. И вполне вероятно, что я где-то ошибся, уж очень существенная разница по времени. Пожалуйста, покажи свои выкладки.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113625
Фотография MaxU
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 Oracle X-pert,

[quote]
Syt' proverki::
select * from my_tab
where UTL_RAW.COMPARE(colN,utl_raw.cast_tow_raw('MY PARAMETER')) = 0;
a ne select bitand(bit1, bit2)...
[/quote]


я что-то совсем запутался - я не понял что с чем это необходимо сравнивать (в твоем понимании/видении) и как это коррелирует с вопросом, заданным автором топика??

my guess:

UTL_RAW.COMPARE(colN,utl_raw.cast_tow_raw('MY PARAMETER')) = 0

bitand(col1,N)

??
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113638
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
pust' col1 v tablize sodergit codes stroko parameters:
' work path screen size ' etc;
zapisi po prinzipy one-to-many::

1 user1 'c:\'
2 user1 'c:\ 800x600'
3 user1 'c:\ 800x600 all forms' etc.

Col2 codergit raw strok.
togda i est:
select user_profile from my_tab
where UTL_RAW.COMPARE(co2,utl_raw.cast_tow_raw('c:\ 800x600')) = 0.
poluchite stroky nomer 2;

Tak rabotaet bol'shinstvo modelei 'SAMSUNG' cell phones { color screen }.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113682
Фотография MaxU
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2 Oracle X-pert,

я не совсем понимаю как это соотносится с вопросом автора топика и в чем выигрыш данного подхода по сравнению с использованием битовых масок целых чисел??
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113689
Фотография Denis Popov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
А зачем мне использовать RAW, если я могу использовать VARCHAR2, построить индекс по этому полю и спросить: where col2 = 'c:\ 800x600'?. Проясни свою структуру, задача: есть сущности "ПОЛЬЗОВАТЕЛЬ" и "СВОЙСТВО". Как указать, что данный пользователь имеет такие-то свойства? Как выбрать пользователей, имеющих _набор_ (чуешь, набор) данных свойств? Как сформировать весь список свойств данного пользователя?

По моему мнению, в таких задачах существование таблицы-справочника возможных свойств и таблицы отношений пользователь-свойство отнюдь не считается излишним "дрыгоножеством и рукомашеством" ((с) Стругацкие). Об этом говорилось в самом начале топика. Ну а уж если клиентскому приложению надо, на лету формировал строку бит или строку свойств.

И еще, как в вышеприведенном примере будет выглядеть запрос:
select user_profile from my_tab where [col2 содержит 'c:\ 800x600'] ?
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113692
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Problema v tom, chto:

a) realizovat' logiku AND t.e.
where A = B
and a = C
and b = D
( sravni:: a in (b,c,d) or a like B etc.)
b) realizuemye selects obychno delaut Merjoin.
chto ne luchim obrazom skazyvaetsya na performance
( xample: where a = b
union
where a = c etc)
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113719
Фотография Denis Popov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Еще раз: пожалуйста, проясни свою структуру таблиц. Требуется очень много времени для догадок, что ты имеешь в виду. Покажи самое простое: есть 2 пользователя, U1 и U2. Есть 2 свойства P1 и P2. U1 имеет свойство P1, U2 имеет свойства P1 и P2.

1. Выбери все свойства пользователя U1.
2. Выбери все свойства пользователя U2.
3. Выбери всех пользователей, имеющих только свойство U1.
4. Выбери всех пользователей, имеющих только свойство U2.
5. Выбери всех пользователей, имеющих свойство U1 и U2.
6. Выбери всех пользователей, имеющих свойство U1 или U2.

Естественно, следует задействовать тип данных RAW.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113727
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Punkt 5.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113743
Фотография Denis Popov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Что означает "Punkt 5."? Как выглядит структура таблиц? Как выглядят запросы?
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113781
Фотография Oracle X-pert
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
create table DEVICE_MASKS
(
DEVICE_ID NUMBER not null,
PARAMETER_NAME VARCHAR2(100) not null,
FORMAT_REF NUMBER not null,
FORMAT_NAME VARCHAR2(100),
STRING_MASKS VARCHAR2(2000),
BIT_MASK RAW(2000),
STATUS NUMBER,
CREATOR VARCHAR2(100),
CHANGED_BY VARCHAR2(100),
DATE_CREATED DATE default sysdate,
LAST_UPDATE DATE default sysdate
)
DEVICE_ID PARAMETER_NAME FORMAT_REF FORMAT_NAME STRING_MASKS BIT_MASK
1 IMAGE_FORMAT 1 JPG JPG 4A5047
1 IMAGE_FORMAT 2 GIF JPG,GIF 4A50472C474946
1 IMAGE_FORMAT 3 PNG JPG,GIF,PNG 4A50472C4749462C504E47
1 IMAGE_FORMAT 4 WBMP JPG,GIF,PNG,WBMP 4A50472C4749462C504E472C57424D50
1 IMAGE_FORMAT 5 NOL JPG,GIF,PNG,WBMP,NOL 4A50472C4749462C504E472C57424D502C4E4F4C
1 IMAGE_FORMAT 6 VIS JPG,GIF,PNG,WBMP,NOL,VIS 4A50472C4749462C504E472C57424D502C4E4F4C2C564953
1 MELODY_FORMAT 2 MID BUZ,MID 42555A2C4D4944
1 MELODY_FORMAT 3 MA1 BUZ,MID,MA1 42555A2C4D49442C4D4131
1 MELODY_FORMAT 4 MA2 BUZ,MID,MA1,MA2 42555A2C4D49442C4D41312C4D4132
1 MELODY_FORMAT 5 MA3 BUZ,MID,MA1,MA2,MA3 42555A2C4D49442C4D41312C4D41322C4D4133
1 MELODY_FORMAT 6 CMX BUZ,MID,MA1,MA2,MA3,CMX 42555A2C4D49442C4D41312C4D41322C4D41332C434D58
1 MELODY_FORMAT 7 AMR BUZ,MID,MA1,MA2,MA3,CMX,AMR 42555A2C4D49442C4D41312C4D41322C4D41332C434D582C414D52
1 MELODY_FORMAT 1 BUZ BUZ 42555A


Select * from DEVICE_MASKS
where = UTL_RAW.COMPARE(BIT_MASK, UTL_RAW.CAST_TO_RAW('JPG,GIF,PNG,WBMP')) = 0;


0.071 sec ( 8 700 000 rows) Index na bit_mask otsytstvuet.
...
Рейтинг: 0 / 0
Доступ к битам поля
    #32113805
Фотография Denis Popov
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Что сказать... "Если звезды зажигают - значит, это кому-нибудь нужно". Подобная структура говорит о том, что либо над ней долго шаманили в рамках _конкретной_задачи_, либо откуда-то перетащили, где подобный подход был единственно возможным. Свойства неравнозначны, к примеру, GIF автоматом подразумевает JPG, что опять же убеждает меня с своих выводах. Таблица прямо-таки затачивалась под один или несколько конкретных запросов. Теперь понятен упор на AND и полное игнорирование всего остального. Еще что могу сказать: ИМХО вряд ли стоит проектировать с нуля систему именно таким образом. Может быть, к подобному решению придется прибегнуть впоследствии, но начинать с этого, особенно занимаясь не "'SAMSUNG' cell phones { color screen }", а чем нибудь другим, я бы не стал.
...
Рейтинг: 0 / 0
36 сообщений из 36, показаны все 2 страниц
Форумы / Oracle [игнор отключен] [закрыт для гостей] / Доступ к битам поля
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


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