Is there a SQL equivalent to #define?
I am using NUMBER(7) for ID's in my DB and I'd like to do something like:
#define ID NUMBER(7)
Then I could use ID in the creation of my tables:
CREATE table Person (
PersonID ID,
Name VARCHAR2(31)
)
This will allow me to easily change the type of all of my IDs if I realize I need more/less space later.
In SQL Plus scripts you can use a substitution variable like this:
DEFINE ID = "NUMBER(7)"
CREATE table Person (
PersonID &ID.,
Name VARCHAR2(31)
);
Basic definitions (similar to the C #define) are called inquiry directives. the inquiry directive cannot be used to define macros.
You can read about inquiry directives here but I think that what you need it's a simple constant.
constant_name CONSTANT datatype := VALUE;
No, there's no way to make this sort of dynamic definition in Oracle. Although Oracle does have the concept of user-defined column types that let you define this globally in a single object, once you create a table that has a column of this type the definition is frozen and you'll get an "ORA-02303: cannot drop or replace a type with type or table dependents" if you try to redefine the type.
I'd Strongly recommend getting a copy of PowerDesigner, which you let you do this through the use of domains.
This code declare two constants. We aren't going to use the constants itself, but their types.
In the create table statement, we declare Name and Blood as "The same type of blood_type and name_type". If later we need more space, we only have to change the types of the constants and all the fields declared with %TYPE in the script will be affected. I hope it help you.
DECLARE
blood_type CONSTANT CHAR;
name_type CONSTANT varchar2(10);
BEGIN
create table patient (
Name name_type%TYPE,
Blood blood_type%TYPE
)
END;
/
EDITED: as dpbradley said there is a problem with this code. Oracle don't let create tables directly inside a begin-end block. The DBMS_SQL package has to be used to create a table dinamically and this would make the solution unreadable and uncomfortable. Sorry.
Related
I am trying to write a stored procedure to let a dev assign new user identities to a specified group when they don't already have one (i.e. insert a parameter and the output of a select statement into a joining table) without hand-writing every pair of foreign keys as values to do so. I know how I'd do it in T-SQL/SQL Server but I'm working with a preexisting/unfamiliar Postgres database. I would strongly prefer to keep my stored procedures as LANGUAGE SQL/BEGIN ATOMIC and this + online examples being simplified and/or using constants has made it difficult for me to get my bearings.
Apologies in advance for length, this is me trying to articulate why I do not believe this question is a duplicate based on what I've been able to find searching on my own but I may have overcorrected.
Schema (abstracted from the most identifying parts; these are not the original table names and I am not in a position to change what anything is called; I am also leaving out indexing for simplicity's sake) is like:
create table IF NOT EXISTS user_identities (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY NOT NULL,
[more columns not relevant to this query)
)
create table IF NOT EXISTS user_groups (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY NOT NULL,
name TEXT NOT NULL
)
create table IF NOT EXISTS group_identities (
user_id BIGINT REFERENCES user_identities(id) ON DELETE RESTRICT NOT NULL,
group_id BIGINT REFERENCES user_groups(id) ON DELETE RESTRICT NOT NULL
)
Expected dev behavior:
Add all predetermined identities intended to belong to a group in a single batch
Add identifying information for the new group (it is going to take a lot of convincing to bring the people involved around to using nested stored procedures for this if I ever can)
Bring the joining table up to date accordingly (what I've been asked to streamline).
If this were SQL Server I would do (error handling omitted for time and putting aside whether EXCEPT or NOT IN would be best for now, please)
create OR alter proc add_identities_to_group
#group_name varchar(50) NULL
as BEGIN
declare #use_group_id int
if #group_name is NULL
set #use_group_id = (select Top 1 id from user_groups where id not in (select group_id from group_identities) order by id asc)
ELSE set #use_group_id = (select id from user_groups where name = #group_name)
insert into group_identities (user_id, group_id)
select #use_group_id, id from user_identities
where id not in (select user_id from group_identities)
END
GO
Obviously this is not going to fly in Postgres; part of why I want to stick with atomic stored procedures is staying in "neutral" SQL, both to be closer to my comfort zone and because I don't know what other languages the database is currently set up for, but my existing education has played kind of fast and loose with differentiating what was T-SQL specific at any point.
I am aware that this is not going to run for a wide variety of reasons because I'm still trying to internalize the syntax, but the bad/conceptual draft I have written so that I have anything to stare at is:
create OR replace procedure add_identities_to_groups(
group_name text default NULL ) language SQL
BEGIN ATOMIC
declare use_group_id integer
if group_name is NULL
set use_group_id = (select Top 1 id from user_groups
where id not in (select user_id from group_identities)
order by id asc)
ELSE set use_group_id = (select id from user_groups where name = group_name) ;
insert into group_identities (group_id, user_id)
select use_group_id, id from user_identities
where id not in (select user_id from group_identities)
END ;
GO ;
Issues:
Have not found either answers for how to do this with the combination of a single variable and a column with BEGIN ATOMIC or hard confirmation that it wouldn't work (e.g. can atomic stored procedures just not accept parameters? I cannot find an answer to this on my own). (This is part of why existing answers that I can find here and elsewhere haven't been clarifying for me.)
~~Don't know how to compensate for Postgres's not differentiating variables and parameters from column names at all. (This is why examples using a hardcoded constant haven't helped, and they make up virtually all of what I can find off StackOverflow itself.)~~ Not a problem if Postgres will handle that intelligently within the atomic block but that's one of the things I hadn't been able to confirm on my own.
Google results for "vanilla" SQL unpredictably saturated with SQL Server anyway, while my lack of familiarity with Postgres is not doing me any favors but I don't know anyone personally who has more experience than I do.
because I don't know what other languages the database is currently set up for
All supported Postgres versions always include PL/pgSQL.
If you want to use procedural elements like variables or conditional statements like IF you need PL/pgSQL. So your procedure has to be defined with language plpgsql - that removes the possibility to use the ANSI standard BEGIN ATOMIC syntax.
Don't know how to compensate for Postgres's not differentiating variables and parameters from column names at all.
You don't. Most people simply using naming conventions to do that. In my environment we use p_ for parameters and l_ for "local" variables. Use whatever you prefer.
Quote from the manual
By default, PL/pgSQL will report an error if a name in an SQL statement could refer to either a variable or a table column. You can fix such a problem by renaming the variable or column, or by qualifying the ambiguous reference, or by telling PL/pgSQL which interpretation to prefer.
The simplest solution is to rename the variable or column. A common coding rule is to use a different naming convention for PL/pgSQL variables than you use for column names. For example, if you consistently name function variables v_something while none of your column names start with v_, no conflicts will occur.
As documented in the manual the body for a procedure written in PL/pgSQL (or any other language that is not SQL) must be provided as a string. This is typically done using dollar quoting to make writing the source easier.
As documented in the manual, if you want to store the result of a single row query in a variable, use select ... into from ....
As documented in the manual an IF statement needs a THEN
As documented in the manual there is no TOP clause in Postgres (or standard SQL). Use limit or the standard compliant fetch first 1 rows only instead.
To avoid a clash between names of variables and column names, most people use some kind of prefix for parameters and variables. This also helps to identify them in the code.
In Postgres it's usually faster to use NOT EXISTS instead of NOT IN.
In Postgres statements are terminated with ;. GO isn't a SQL command in SQL Server either - it's a client side thing supported by SSMS. To my knowledge, there is no SQL tool that works with Postgres that supports the GO "batch terminator" the same way SSMS does.
So a direct translation of your T-SQL code to PL/pgSQL could look like this:
create or replace procedure add_identities_to_groups(p_group_name text default NULL)
language plpgsql
as
$$ --<< start of PL/pgSQL code
declare --<< start a block for all variables
l_use_group_id integer;
begin --<< start the actual code
if p_group_name is NULL THEN --<< then required
select id
into l_use_group_id
from user_groups ug
where not exists (select * from group_identities gi where gi.id = ug.user_id)
order by ug.id asc
limit 1;
ELSE
select id
into l_use_group_id
from user_groups
where name = p_group_name;
end if;
insert into group_identities (group_id, user_id)
select l_use_group_id, id
from user_identities ui
where not exists (select * from group_identities gi where gi.user_id = ui.id);
END;
$$
;
I have I table consisting of 3 columns: system, module and block. Table is filled in a procedure which accepts system, module and block and then it checks if the trio is in the table:
select count(*) into any_rows_found from logs_table llt
where system=llt.system and module=llt.module and block=llt.block;
If the table already has a row containing those three values, then don't write them into the table and if it doesn't have them, write them in. The problem is, if the table has values 'system=a module=b block=c' and I query for values 'does the table have system=a module=d block=e' it returns yes, or, to be precise, any_rows_found=1. Value 1 is only not presented when I send a trio that doesn't have one of it's values in the table, for example: 'system=g module=h and block=i'. What is the problem in my query?
Problem is in this:
where system = llt.system
Both systems are the same, it is as if you put where 1 = 1, so Oracle is kind of confused (thanks to you).
What to do? Rename procedure's parameters to e.g. par_system so that query becomes
where llt.system = par_system
Another option (worse, in my opinion) is to precede parameter's name with the procedure name. If procedure's name was e.g. p_test, then you'd have
where llt.system = p_test.system
From the documentation:
If a SQL statement references a name that belongs to both a column and either a local variable or formal parameter, then the column name takes precedence.
So when you do
where system=llt.system
that is interpreted as
where llt.system=llt.system
which is always true (unless it's null). It is common to prefix parameters and local variables (e.g. with p_ or l_) to avoid confusion.
So as #Littlefoot said, either change the procedure definition to make the parameter names different to the column names, or qualify the parameter names with the procedure name - which some people prefer but I find more cumbersome, and it's easier to forget and accidentally use the wrong reference.
Root cause is alias used for table name.
where system=llt.system and module=llt.module and block=llt.block;
Table name alias in select query and input to procedure having the same name(i.e. llt
). You should consider either renaming one of them.
I am curious about syntax usage with PL/SQL collection type creations. What is the difference between is table of and as table of when creating a PL/SQL nested table collection type, if any? I've seen only is table of in the Oracle help documentation but code I've come across uses both is table of and as table of when creating the collection type. I tried both and both statements appear to execute at the same speed and hold data as intended.
For example, for object type
create or replace type new_emp_ot is object
(
ssn number(9),
lname varchar2(200),
fname varchar2(200)
);
is there any discernible difference between how Oracle processes
create or replace type new_emp_nt as table of new_emp_ot;
and
create or replace type new_emp_nt is table of new_emp_ot;
?
IS and AS are interchangeable in the CREATE TYPE syntax, there is no difference in this case.
Although the syntax diagram is incorrect... it makes it look like IS/AS are optional, but you can't actually omit them.
I would like to implement something like the following pseudo-code. Let say I have table named T_TMP_TABLE with column 'hour', 'day', and 'year'. The table name is used as an input parameter for create_types_fn function. Let's assume that I can get a list of column names and store it to column_name_array. Now, I need to create "custom type" using those column names. The reason is that the function will return table as an output, and the columns of the returned table would be the same ('hour', 'day', and 'year')
Briefly speaking, I have a table and I need output as table-format with same column names.
Am I able to do this? any suggestion or recommendation would be much appreciated!!
CREATE OR REPLACE FUNCTION create_types_fn (table_name in varchar2)
....
begin
array column_name_array = get_column_name_in_array_by_table_name(table_name)
CREATE OR REPLACE TYPE my_type AS OBJECT (
column_name_array(0) NUMBER,
column_name_array(1) NUMBER,
column_name_array(2) VARCHAR2(30)
);
CREATE OR REPLACE type my_table AS TABLE OF my_type ;
select * bulk collect into my_table ;
end
EDIT
Here is what I am trying to do
I am trying to compare two tables and return rows if there are any difference. So, I think the output should be table-format. Since every table has different column names, I think it would be nice if I can make generic function..
If you are trying to compare the data in two different tables, you would almost certainly want to use the dbms_comparison package rather than writing your own. That populates a generic structure rather than creating new types for each table.
I'm trying to declare a variable in a simple sql script to create some tables in a schema, but it's not working.
Here's a snippet of my sql script:
DEF SCHEMA_NAME = MY_SCHEMA;
CREATE TABLE &SCHEMA_NAME.BOOK
(
BOOK_ID INTEGER
);
That's creating a table with the table name MY_SCHEMABOOK instead of a table named BOOK in the schema MY_SCHEMA.
The script output in Oracle Sql Developer says:
old:CREATE TABLE &SCHEMA_NAME.BOOK
(
BOOK_ID INTEGER
)
new:CREATE TABLE MY_SCHEMABOOK
(
BOOK_ID INTEGER
)
table MY_SCHEMABOOK created.
If that helps. Also, it seems that changing it to &SCHEMA_NAME..BOOK does make it work like I want it to, but having to put two periods doesn't make sense to me. Can anyone tell me what I'm doing wrong?
SET CON[CAT] {. | c | ON | OFF}
Sets the character used to terminate a substitution variable reference
when SQL*Plus would otherwise interpret the next character as a part
of the variable name.
SQL*Plus resets the value of CONCAT to a period when you switch CONCAT on.
http://docs.oracle.com/cd/B19306_01/server.102/b14357/ch12040.htm#sthref2722
SQL Developer works the same way - your first period is interpreted as a substitution variable terminator. So, it is perfectly valid to use two consequent periods in this case.