我需要将所有表的主键列临时设置为 GENERATED BY DEFAULT 而不是 ALWAYS。我当然可以自己编译一个列表,但是是否可以“一次性”为特定模式中的所有表设置它?谢谢!
问问题
624 次
2 回答
0
如果您使用的是 Mainframe DB2,那么此命令应该适合您(假设您的意思是键是一个 Identity 列,始终生成,还有其他默认代码,您可以在Info Center 页面上看到):
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
这只会生成所需的命令。您需要自己执行它们。
于 2013-03-01T14:21:32.647 回答
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
于 2013-03-01T15:44:38.687 回答