开发者

How can I conditionally construct a table name for an SQL CREATE TABLE statement?

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?


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜