|
|
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Доброго времени суток! Ситуация следующая. Некоторое поле таблицы хотелось бы использовать для настройки индивидуальных параметров просмотра/редактирования данных в приложении применительно для каждого пользователя (чтобы не создавать ключи в реестре и ini-файлы). Естесственно, нужно чтобы пользователи при этом друг другу не мешали. Вроде бы, можно реализовать это как работу с байтами (т.е. порядковый номер символа в строке определяет пользователя). Однако если пользователей много, то в достаточно большой таблице пропадает зазря куча места. Может быть существует вариант более изящный (например с битами)? Заранее благодарен. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 26.02.2003, 16:51 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Postroi maska as RAW(n) ili LONG RAW. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 26.02.2003, 17:02 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
мне кажется это изврат, лучеш по признаку их разнеси (поле - пользоваетель и нормальна работай) ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 26.02.2003, 17:10 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Komanda UTL_RAW.Compare rabotaet bystree vsego! ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 26.02.2003, 19:04 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Прежде всего извиняюсь за молчание. 2new one: Не подходит, а если у тебя сотни пользователей? 2Oracle X-pert: Команды raw(n) в 8-ке нет или я чего-то не понял. А использовать для этих целей обычный number не получится? А хотелось бы именно с ним работать. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 08:24 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 09:10 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Но мне-то нужно вытащить из поля определенный бит, а не просто узнать что колонки содержат разные значения. Кроме того, кажется мне, что пример просто выдает 0 для одинаковых значений и 1 для разных. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 11:59 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Т.е., не затрагивая структуру БД, тебе требуются битовые операции в Oracle? Есть функция BITAND: http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/functions14a.htm#SQLRF00612 Если потребуются функции для других битовых операций, могу кинуть функции. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 12:06 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Спасибо. Страница у меня недоступна, попробую позже. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 12:26 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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; ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 12:36 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
http://www.jlcomp.demon.co.uk/faq/bitwise.html использование UTL_RAW в данном случае - неоправданное расходование ресурсов сервера (для преобразования типов) ! ЗЫ не совсем понятно почему Ларри & Co не удосужились реализовать "Bitwise OR" и "Bitwise XOR" ??? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 13:53 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Замечание для Oracle X-pert: не надо опубликовывать такие большие документы. Пересылайте тому кто просил его по почте или давайте ссылку на информацию ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 14:22 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Поддерживаю new one - это изврат А если сделать таблицу пользователь настройки Много пользователей много строк. Место зря не расходуется. Или надо настройки привязать к строке. Тогда еще одно поле - id_строки в таблице. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 14:39 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
2SERG1257 А если у тебя в схеме пара десятков таблиц по 100000 каждой и для каждой из них нужно сохранить информацию о том какой пользователь какие столбцы пометил для своей (индивидуальной) выборки? Неверно. Не подходит. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 27.02.2003, 15:29 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
BABY только там и делай, как я посоветовал... создай таблицу настроек и все будет нормальна (я делал, все работало, правда может для других целей...) ну у меня на сервере порядка 400 таблиц и окола 150 пользователей юзающих их. без проблем все решается. а по битаем, ты просто замудохаешься хотя может тебе так больше нравится Ты може точно скажи что ты хочешь, и мы найдем тебе решение ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 11:24 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 11:48 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
2 автор топика, я часто использую данный подход, он себя оправдывает при небольших таблицах ( в кот. присутствует "запакованное" поле(я) ), т.к. при использовании конструкции: Код: plaintext т.е. если я правильно понял твою задачу, то я бы использовал приблизительно след. структуру - Код: plaintext т.е. в таблице будет (UsersNo * TablesNo) строк... 2 Oracle X-pert, ну давай начнем разбор полетов... :) моя идея была использовать функцию BITAND, ты предложил использовать UTL_RAW, т.е. ты хочешь сказать что конструкция типа: Код: plaintext 1. будет работать быстрее чем: Код: plaintext ??? чего то мне слабо верится... ;) ЗЫ при использовании/хранении битовых масок в поле типа NUMBER существует ограничение на кол-во хранимых битовых полей, при использовании RAW такого ограничения нет - с этой точки зрения я могу понять использование RAW... ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 12:39 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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... ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 12:56 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
2 Oracle X-pert, а как на счет реальных тестов? ну там создаешь табличку (100000) записей и пробуешь оба подхода, выполнив предварительно: SQL> set timing on что-то мне подсказывает что мой вариант будет работать быстрее... ;) ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 13:22 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Testirovali v Oracle (UK) na tables with 10000000rows/1.8 G... ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 14:14 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Kstati, SEMA toge eto testirovala.... ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 14:14 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
а где можно взглянуть на результаты? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 16:26 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Я не претендую на окончательность ответа, но вот что у меня получилось. Пояснение: 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. Получается 00:52.08 у BITAND() против 02:33.00 у UTL_RAW.BIT_AND(). ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 17:06 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
2 Denis Popov, спасибо что не поленился тест написать! :) 2 Oracle X-pert, я все бы еще не отказался взглянуть на результаты Oracle (UK)... ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 28.02.2003, 17:26 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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, ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 02.03.2003, 09:15 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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. Код: plaintext 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. Заметь, два этих запроса отвечают на совершенно разные вопросы, "AND" и "=". Я подозреваю, что загвоздка может быть в постоянном вызове UTL_RAW.CAST_TO_RAW. И вполне вероятно, что я где-то ошибся, уж очень существенная разница по времени. Пожалуйста, покажи свои выкладки. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 11:38 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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) ?? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 13:49 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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 }. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 14:08 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
2 Oracle X-pert, я не совсем понимаю как это соотносится с вопросом автора топика и в чем выигрыш данного подхода по сравнению с использованием битовых масок целых чисел?? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 14:56 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
А зачем мне использовать RAW, если я могу использовать VARCHAR2, построить индекс по этому полю и спросить: where col2 = 'c:\ 800x600'?. Проясни свою структуру, задача: есть сущности "ПОЛЬЗОВАТЕЛЬ" и "СВОЙСТВО". Как указать, что данный пользователь имеет такие-то свойства? Как выбрать пользователей, имеющих _набор_ (чуешь, набор) данных свойств? Как сформировать весь список свойств данного пользователя? По моему мнению, в таких задачах существование таблицы-справочника возможных свойств и таблицы отношений пользователь-свойство отнюдь не считается излишним "дрыгоножеством и рукомашеством" ((с) Стругацкие). Об этом говорилось в самом начале топика. Ну а уж если клиентскому приложению надо, на лету формировал строку бит или строку свойств. И еще, как в вышеприведенном примере будет выглядеть запрос: select user_profile from my_tab where [col2 содержит 'c:\ 800x600'] ? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 15:04 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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) ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 15:17 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Еще раз: пожалуйста, проясни свою структуру таблиц. Требуется очень много времени для догадок, что ты имеешь в виду. Покажи самое простое: есть 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. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 15:38 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Что означает "Punkt 5."? Как выглядит структура таблиц? Как выглядят запросы? ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 15:54 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
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. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 16:37 |
|
||
|
Доступ к битам поля
|
|||
|---|---|---|---|
|
#18+
Что сказать... "Если звезды зажигают - значит, это кому-нибудь нужно". Подобная структура говорит о том, что либо над ней долго шаманили в рамках _конкретной_задачи_, либо откуда-то перетащили, где подобный подход был единственно возможным. Свойства неравнозначны, к примеру, GIF автоматом подразумевает JPG, что опять же убеждает меня с своих выводах. Таблица прямо-таки затачивалась под один или несколько конкретных запросов. Теперь понятен упор на AND и полное игнорирование всего остального. Еще что могу сказать: ИМХО вряд ли стоит проектировать с нуля систему именно таким образом. Может быть, к подобному решению придется прибегнуть впоследствии, но начинать с этого, особенно занимаясь не "'SAMSUNG' cell phones { color screen }", а чем нибудь другим, я бы не стал. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 03.03.2003, 17:05 |
|
||
|
|

start [/forum/topic.php?all=1&fid=52&tid=1991636]: |
0ms |
get settings: |
7ms |
get forum list: |
18ms |
check forum access: |
5ms |
check topic access: |
5ms |
track hit: |
171ms |
get topic data: |
7ms |
get forum data: |
2ms |
get page messages: |
43ms |
get tp. blocked users: |
1ms |
| others: | 234ms |
| total: | 493ms |

| 0 / 0 |
