如何从 PL/SQL 过程动态创建具有动态数据类型的表
CREATE OR REPLACE PROCEDURE p_create_dynamic_table IS
v_qry_str VARCHAR2 (100);
v_data_type VARCHAR2 (30);
BEGIN
SELECT data_type || '(' || data_length || ')'
INTO v_data_type
FROM all_tab_columns
WHERE table_name = 'TEST1' AND column_name = 'ZIP';
FOR sql_stmt IN (SELECT * FROM test1 WHERE zip IS NOT NULL)
LOOP
IF v_qry_str IS NOT NULL THEN
v_qry_str := v_qry_str || ',' || 'zip_' || sql_stmt.zip || ' ' ||v_data_type;
ELSE
v_qry_str := 'zip_' || sql_stmt.zip || ' ' || v_data_type;
END IF;
END LOOP;
IF v_qry_str IS NOT NULL THEN
v_qry_str := 'create table test2 ( ' || v_qry_str || ' )';
END IF;
EXECUTE IMMEDIATE v_qry_str;
COMMIT;
END p_create_dynamic_table;
有更好的方法吗?
CREATE OR REPLACE PROCEDURE p_create_dynamic_table IS
v_qry_str VARCHAR2 (100);
v_data_type VARCHAR2 (30);
BEGIN
SELECT data_type || '(' || data_length || ')'
INTO v_data_type
FROM all_tab_columns
WHERE table_name = 'TEST1' AND column_name = 'ZIP';
FOR sql_stmt IN (SELECT * FROM test1 WHERE zip IS NOT NULL)
LOOP
IF v_qry_str IS NOT NULL THEN
v_qry_str := v_qry_str || ',' || 'zip_' || sql_stmt.zip || ' ' ||v_data_type;
ELSE
v_qry_str := 'zip_' || sql_stmt.zip || ' ' || v_data_type;
END IF;
END LOOP;
IF v_qry_str IS NOT NULL THEN
v_qry_str := 'create table test2 ( ' || v_qry_str || ' )';
END IF;
EXECUTE IMMEDIATE v_qry_str;
COMMIT;
END p_create_dynamic_table;
Is there any better way of doing this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我没看错的话,您似乎想创建一个新表,其中每个邮政编码包含一列。
我认为您提出的答案是实现您既定目标的最佳方法。我想补充一点,您可能想要对用于循环的游标进行排序,这将确保列始终处于相同的顺序。
然而,你的目标非常可疑。最好退一步考虑创建此表是否真的是解决问题的正确方法。这似乎是一次大规模的非规范化,维护起来将是一场噩梦。在不知道为什么要采用这种方法的情况下,我无法提供更好的解决方案,但是,尽管如此,我认为可能有一个。
If I'm reading this correctly, it appears that you want to create a new table containing one column for each zip code.
I think the answer you came up with is the best possible way to accomplish your stated goals. I would add that you probably want to sort the cursor used for the loop, which will ensure that the columns are always in the same order.
However, your goal is highly suspect. It might be better to take a step back and consider whether creating this table is really the right way to solve your problem. This appears to be a massive de-normalization and will be a nightmare to maintain. Without knowing why you're taking this approach I can't offer a better solution, but, nonetheless, I think there probably is one.
为什么不在表上创建一个视图,该视图仅包含带有 zip 的列?
这样您就不需要复制数据。或者说你的具体要求是什么?
Why don't you create a view on the table, which contains only those columns with a zip?
That way you don't need to copy the data. Or what are your exact requirements?