2012-04-04 114 views
6

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

我想:

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'); 

,但没有成功(如下):

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] 

如何这个约束应该被正确删除?

顺便说一句:

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) 

似乎返回正确的输出。

回答

8

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

select distinct constraint_name from information_schema.constraints 
where table_name='PUBLIC_PARTNER' and column_list='INFO' 

然后拿到标识符名称,然后运行该语句

ALTER TABLE PUBLIC_PARTNER DROP CONSTRAINT <xxx> 
+0

谢谢,托马斯!我希望你亲自回答我的问题:)问题是你的解决方案对我来说显而易见,无论如何我会接受你的答案。坏的是我需要它来自动化我的德尔塔脚本,而不需要手动干预:(((( – Alec 2012-04-05 07:34:49

+1

这个我得到了“Constraint not found”),它为我工作的“constraint_name”而不是“unique_index_name”,这样select就是'从formation_schema.constraints 选择不同constraint_name命令在表格名= 'PUBLIC_PARTNER' 和column_list中= UNIQUE'' 我的H2的版本是1.3 'INFO'' 一个还可另外通过添加'AND constraint_type =限制约束类型' .166 btw。 – MartinGrotzke 2012-07-19 07:47:41

+0

@MartinGrotzke谢谢!我已经更新了我的答案(在“information_schema”中也有一个错字)。 – 2012-07-19 10:04:18

5

你可以使用一个用户定义的函数执行动态创建SQL语句。首先创建execute别名(仅一次):

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

然后调用这个方法:

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')); 

...其中execute是运行语句的用户定义的函数。

+1

这将是用户定义的函数: 'CREATE ALIAS IF NOT EXISTS EXECUTE AS $$ 空隙的ExecuteSQL(连接康恩,字符串SQL)抛出的SQLException { conn.createStatement()的executeUpdate(SQL); } $$;' – MartinGrotzke 2012-07-19 07:22:52

+0

使用此解决方案,但它失败,'不支持的功能:“VARCHAR +”; SQL语句:'。我的代码:'调用execute('ALTER TABLE DAILY_AGGREGATES DROP CONSTRAINT'+ (从information_schema.constraints中选择不同的constraint_name,其中table_name ='DAILY_AGGREGATES'和constraint_type ='PRIMARY KEY'));' – smajlo 2014-10-07 15:36:55

+3

在SQL中,'+'是不用于连接字符串。相反,使用'||'。如下所示:'调用execute('ALTER TABLE DAILY_AGGREGATES DROP CONSTRAINT'||(从information_schema中选择不同的constraint_name)。约束where table_name ='DAILY_AGGREGATES'和constraint_type ='PRIMARY KEY'));' – 2014-10-07 18:38:57