如何有条件地为 SQL CREATE TABLE 语句构造表名?
在 SQL 存储过程中,我希望能够构造表名并创建它。
示例:我刚刚登录公司 03 下的数据库,但客户表不存在,因此我希望过程CREATE TABLE CUSTOMER03
。
有没有办法将company_id char(2) 附加到CUSTOMER 并将其提供给CREATE TABLE 语句?也许喜欢
CREATE TABLE $tablename or $tablename+company_id?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Oracle 中,语法类似于
但是这可能是一个非常糟糕的主意。六个月后,您将需要向表中添加一列,并且需要确定需要将其添加到哪些表中。
另外,Oracle 中的存储过程需要(现有表的)固定表名,否则您必须通过动态 SQL 引用所有内容,这很痛苦。
最好有一个以 company_id 作为属性的客户表。然后使用细粒度访问控制安全地过滤company_id以控制谁可以看到什么公司的数据。
In Oracle the syntax would be something like
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.
您需要使用动态 SQL 例如:(
已测试)
You would need to use dynamic SQL eg:
(tested)
对
CREATE TABLE
语句使用IF NOT EXISTS
修饰符。这将导致仅当表尚不存在时才创建该表。Use the
IF NOT EXISTS
modifier to theCREATE TABLE
statement. This will cause the table to be created only if it does not already exist.