Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql generate unique table/view name

Tags:

sql

postgresql

I want to create some mad robust code. I want to take a query as a string, create a temporary view / table to store the results, use it, then drop the table. I want to use a name that is guaranteed to not already exist in the database. Is there an SQL command to generate a unique table name? I'm using postgresql if this is implementation-specific.

like image 528
Claudiu Avatar asked Jun 08 '10 23:06

Claudiu


2 Answers

You could use a temporary table. Temporary tables are invisible to other connections. If a permanent table with the same name as the temporary table exists, the permanent table is invisible to the current connection.

CREATE TEMPORARY TABLE table_name  
(  
 column_name1 data_type(length) constraints,  
 column_name2 data_type(length) constraints,  
 ...

See the PostgreSQL manual page.

like image 113
Andomar Avatar answered Oct 11 '22 08:10

Andomar


I don't know a SQL command to do that but you could just generate one kind of like generating a temp filename: put in the date, some random number, process ID, user's birthday: $table_name = join("_", "temp", $$, rand()*0x1000, time)

In all SQL databases I've used, each session has its own namespace of temporary tables. So you can just create a temp table called "foo" and not worry about it clashing with another thread doing the same thing (on a different connection!). In Oracle, this is specifically a "LOCAL temporary table"- whereas a "GLOBAL temporary table" is seen by all sessions: but only its schema, not its data. In MSSQL, table names are internally bodged to be distinct, but constraint names aren't (are weren't as of SQL Server 2000).

like image 24
araqnid Avatar answered Oct 11 '22 06:10

araqnid