java触发器如何创建表_在java 中执行触发器代码、创表语句

由于程序的需要,在SQLServer 中创建触发器及建表,碰到了在java 代码中执行创建触发器及表。

/**建立中间表*/

public static final String

createMiddleTableSQL =

"CREATE TABLE [dbo].[AlarmsMiddleTbl] ( "

+ " [id] [int] NOT NULL  , "

+ " [DeviceID] [smallint] NULL , "

+ " [Aid] [char] (10) COLLATE Chinese_PRC_BIN NULL , "

+ " [BeginTime] [datetime] NULL , "

+ " [EndTime] [datetime] NULL , "

+ " [Severity] [char] (2) COLLATE Chinese_PRC_BIN NULL , "

+ " [CondType] [char] (25) COLLATE Chinese_PRC_BIN NULL , "

+ " [DetailID] [smallint] NULL , "

+

" [AckNotes] [char] (150) COLLATE Chinese_PRC_BIN NULL , "

+

" [Description] [char] (255) COLLATE Chinese_PRC_BIN NULL , "

+

" [Systemtimes] [char] (30) COLLATE Chinese_PRC_BIN NULL "

+ ") ON [PRIMARY] ";

/**在告警表上创建触发器*/

public static final String createMiddleTblTriggerSQL =

"CREATE   TRIGGER t_alarms "

+ "ON [NTBW].[dbo].[Alarms] "

+ "FOR INSERT, UPDATE "

+ "AS "

+ "DECLARE  @rows int "

+ "SELECT @rows =  @@rowcount "

+ "IF @rows = 0 "

+ "  return "

+

"IF EXISTS(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted) "

+ "BEGIN "

+ "  INSERT INTO [NTBW].[dbo].[AlarmsMiddleTbl] "

+ "  SELECT i.[id], i.[DeviceID], i.[Aid], i.[BeginTime], "

+

"  i.[EndTime], i.[Severity], i.[CondType], i.[DetailID], i.[AckNotes], "

+ "  i.[Description], getdate() from inserted i "

+ "END "

+

"IF EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted) AND "

+ " UPDATE(EndTime) "

+ "BEGIN "

+ "  INSERT INTO [NTBW].[dbo].[AlarmsMiddleTbl] "

+ "  SELECT i.[id], i.[DeviceID], i.[Aid], i.[BeginTime], "

+

"  i.[EndTime], i.[Severity], i.[CondType], i.[DetailID], i.[AckNotes], "

+ "  i.[Description], getdate() from inserted i "

+ "END "

+ "IF @@error <> 0 "

+ "BEGIN "

+ "  RAISERROR('ERROR',16,1) "

+ "  rollback transaction "

+ "  return "

+ "END ";

JAVA中执行以上语句过程:

view plaincopy to clipboardprint?

/**

* 创建中间表或者触发器

*

* @param sql String

* @return boolean 返回语句执行结果,true 成功,false 失败

*/

private boolean createTableOrTrigger(String sql)

{

Connection con = null;

PreparedStatement st = null;

boolean result = false;

try

{

con = dbh.getConnection();

st = con.prepareStatement(sql);

st.execute();

result = true;

dbh.closeConnections(null, st, con);

}

catch (SQLException ex)

{

Log.error("Unable to create :" +

sql + " ,ErrorCode :" + ex.getErrorCode() +

",Exception :" +

ex.getLocalizedMessage());

dbh.closeConnections(null, st, con);

}

return result;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值