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

前端 未结 3 1896
孤独总比滥情好
孤独总比滥情好 2021-01-24 17:51

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

相关标签:
3条回答
  • 2021-01-24 18:39

    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.

    0 讨论(0)
  • 2021-01-24 18:41

    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)

    0 讨论(0)
  • 2021-01-24 18:56

    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 讨论(0)
提交回复
热议问题