可以使用IBM DB2中的一个脚本将所有表设置为GENERATED BY DEFAULT吗?

时间:2013-03-01 11:23:28

标签: db2

我需要暂时将所有表的主键列设置为GENERATED BY DEFAULT而不是ALWAYS。我可以自己编译一个列表,但是可以通过“一次性”为特定模式中的所有表设置它吗?谢谢!

2 个答案:

答案 0 :(得分:0)

如果您使用的是Mainframe DB2,那么此命令应该适合您(假设您的意思是密钥是一个Identity列,始终生成,还有其他默认代码,您可以在{{3}上看到) }):

SELECT 
    'ALTER TABLE ' ||
    RTRIM(TBCREATOR) || '.' || RTRIM(TBNAME) ||
    'ALTER COLUMN ' ||
    RTRIM(NAME) ||
    'SET GENERATED BY DEFAULT;'
FROM SYSIBM.SYSCOLUMNS
WHERE DEFAULT = 'I'
  AND TBCREATOR = @schema

如果您使用的是DB2 for LUW,那么应该这样做:

SELECT 
    'ALTER TABLE ' ||
    RTRIM(TABSCHEMA) || '.' || RTRIM(TABNAME) ||
    'ALTER COLUMN ' ||
    RTRIM(COLNAME) ||
    'SET GENERATED BY DEFAULT;'
FROM SYSCAT.COLUMNS
WHERE GENERATED = 'A'
  AND TABSCHEMA = @schema

这只会生成所需的命令。您需要自己执行它们。

答案 1 :(得分:0)

您可以通过查询目录中的数据来生成查询。我的意思是,你做一个返回alter命令的Select,这个输出被发送到一个文件。在您必须执行该文件的内容之后

(Linux / UNIX的/ Cywgin)

db2 -x "select 'alter table ' || trim(tabschema) || '.' || trim(tabname) || ' alter column ' || colname || ' set generated by default as identity ;' from syscat.columns where tabschema like 'DB2INS%' and keyseq >= 0" > test.sql
db2 -tvf file.sql

但是,您必须检查生成的命令,如果执行,请检查返回的值:

db2 create table t1 \(c1 int not null primary key, c2 int, c3 int\)
db2 create table t2 \(c21 int references t1 \(c1\), c22 int\)
db2 create table t3 \(c30 int, c31 int not null, c32 int not null, c33 int\)
db2 alter table t3 add primary key \(c31, c32\)
db2 create table t4 \(c40 int, c41 int, c42 int, c43 int\)
db2 alter table t4 add constraint fk foreign key \(c42, c43\) references t3

db2 -x "select 'alter table ' || trim(tabschema) || '.' || trim(tabname) || ' alter column ' || colname || ' set generated by default as identity ;' from syscat.columns where tabschema like 'DB2INS%' and keyseq >= 0" > test.sql

db2 -tvf test.sql
alter table DB2INS01.T1 alter column C1 set generated by default as identity
DB20000I  The SQL command completed successfully.
alter table DB2INS01.T3 alter column C31 set generated by default as identity
DB20000I  The SQL command completed successfully.
alter table DB2INS01.T3 alter column C32 set generated by default as identity
DB21034E  The command was processed as an SQL statement because it was not a
valid Command Line Processor command.  During SQL processing it returned:
SQL0372N  A column with data type or attribute ROWID, IDENTITY, security label,
or row change timestamp can only be specified once for a table.
SQLSTATE=428C1