在H2中删除列的唯一约束

Ale*_*lec 7 sql database h2

我尝试删除以前创建的h2中的列的唯一约束info varchar(255) unique.

我试过了:

sql> alter table public_partner drop constraint (select distinct unique_index_name from in
formation_schema.constraints where table_name='PUBLIC_PARTNER' and column_list='INFO');
Run Code Online (Sandbox Code Playgroud)

但没有成功(如下):

Syntax error in SQL statement "ALTER TABLE PUBLIC_PARTNER DROP CONSTRAINT ([*]SELECT DISTI
NCT UNIQUE_INDEX_NAME FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE TABLE_NAME='PUBLIC_PARTNER
' AND COLUMN_LIST='INFO') "; expected "identifier"; SQL statement:
alter table public_partner drop constraint (select distinct unique_index_name from informa
tion_schema.constraints where table_name='PUBLIC_PARTNER' and column_list='INFO') [42001-1
60]
Run Code Online (Sandbox Code Playgroud)

如何正确删除此约束?

顺便说说:

sql> (select unique_index_name from information_schema.constraints where table_name='PUBLI
C_PARTNER' and column_list='INFO');
UNIQUE_INDEX_NAME
CONSTRAINT_F574_INDEX_9
(1 row, 0 ms)
Run Code Online (Sandbox Code Playgroud)

似乎返回正确的输出.

Tho*_*ler 10

在SQL语言中,标识符名称不能是表达式.您需要运行两个语句:

select distinct constraint_name from information_schema.constraints 
where table_name='PUBLIC_PARTNER' and column_list='INFO'
Run Code Online (Sandbox Code Playgroud)

然后获取标识符名称,并运行该语句

ALTER TABLE PUBLIC_PARTNER DROP CONSTRAINT <xxx>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,托马斯!我希望您亲自回答我的问题:)问题是您的解决方案对我来说是显而易见的,无论如何我都会接受您的答案,因为它很有用。坏事是我需要它来自动化我的增量脚本而无需手动干预:((( (2认同)

Tho*_*ler 5

您可以使用用户定义的函数来执行动态创建的语句.首先创建execute别名(只有一次):

CREATE ALIAS IF NOT EXISTS EXECUTE AS $$ void executeSql(Connection conn, String sql) 
throws SQLException { conn.createStatement().executeUpdate(sql); } $$;
Run Code Online (Sandbox Code Playgroud)

然后调用此方法:

call execute('ALTER TABLE PUBLIC_PARTNER DROP CONSTRAINT ' || 
    (select distinct unique_index_name from in formation_schema.constraints 
    where table_name='PUBLIC_PARTNER' and column_list='INFO'));
Run Code Online (Sandbox Code Playgroud)

... execute运行语句的用户定义函数在哪里.

  • 在SQL中,`+`不用于连接字符串.相反,使用`||`.如:`call execute('ALTER TABLE DAILY_AGGREGATES DROP CONSTRAINT'||(从information_schema.constraints中选择distinct constraint_name,其中table_name ='DAILY_AGGREGATES'和constraint_type ='PRIMARY KEY')); (3认同)