问题
Within an SQL stored procedure, I would like to have the ability to construct a table name and create it.
Example: I just logged into my database under company 03 and a customer table does not exist, so I would like for the proc to CREATE TABLE CUSTOMER03
.
Is there a way to append company_id char(2)
to CUSTOMER
and feed it to the CREATE TABLE
statement? maybe like
CREATE TABLE $tablename or $tablename+company_id?
回答1:
You would need to use dynamic SQL eg:
DECLARE @company_id char(2)
SET @company_id = '02'
EXEC('CREATE TABLE CUSTOMER' + @company_id + ' (id int PRIMARY KEY)')
(tested)
回答2:
In Oracle the syntax would be something like
BEGIN
EXECUTE IMMEDIATE 'CREATE TABLE CUSTOMER_'||v_company_id||' (..)';
END;
However this is probably a really bad idea. Six months down the line you'll want to add a column to the table and you'll need to work out which tables you need to add it to.
Also, stored procedures in Oracle need a fixed table name (of an existing table) or you'd have to reference everything through dynamic SQL which is a pain.
Better to have a single customer table with the company_id as an attribute. Then use Fine Grained Access Control to securely filter on the company_id to control who see's what company's data.
回答3:
Use the IF NOT EXISTS
modifier to the CREATE TABLE
statement. This will cause the table to be created only if it does not already exist.
来源:https://stackoverflow.com/questions/4121307/how-can-i-conditionally-construct-a-table-name-for-an-sql-create-table-statement