2016-03-03 35 views
0

我将在Oracle中将值插入到两个表中。当我将记录插入第一个表时,我需要获取该表的Id并需要输入第二个表。使用oracle将记录插入到两个表中

使用我的查询它将值插入第一个表。

public bool AddNewNews(NEWS nws) 
    { 
     bool status = false; 

     try 
     { 

       DatabaseProviderFactory factory = new DatabaseProviderFactory(); 
       Database db = factory.Create("CharikaConString"); 

       con.Open(); 

       string query = @"INSERT INTO NEWS_TBL(NewsID,NAME) 
           VALUES(newsid.nextval,:NAME)"; 


       cmd = db.GetSqlStringCommand(query); 

       db.AddInParameter(cmd, "NAME", DbType.String, nws.NAME); 

       db.ExecuteNonQuery(cmd); 
// In the below commented lines are,I tried to insert second table but not success. 
        // String query2 = "Select newsid.currval"; 

       //string query2 = @"INSERT INTO DTL_TBL(DtlId,desc) VALUES (newsid.currval,nws.Desc)"; 
       // cmd = db.GetSqlStringCommand(query); 

       //db.AddInParameter(cmd, "desc", DbType.String, nws.Desc); 

       // db.ExecuteNonQuery(cmd); 

     } 
     catch (Exception ex) 
     { 

      throw; 
     } 
     finally 
     { 
      con.Close(); 
     } 
     return status; 
    } 
+0

可能重复的[如何获取上次插入的ID?](http://stackoverflow.com/questions/5228780/how-to-get-last-inserted-id) –

+0

你试过了一个简单的谷歌搜索,检查此前发布 - http://stackoverflow.com/questions/1336911/how-to-get-the-generated-id-from-an-inserted-row-using-executescalar – MethodMan

+0

@JuanCarlosOropeza这对于sql服务器,而不是oracle – TechGuy

回答

2

但是您正在使用Oracle序列有办法,你可以抓住该值在初步声明

select newsid.nextval from dual 

,然后使用它作为您的后续插入常规参数?

+0

不知道是否有更好的方法,但这是我总是这样做的! – Ageonix

+0

那么如何将它插入到第二个表? – TechGuy

+0

你会说:double newId = db.executescalar();在上面的select语句中,然后在需要的地方替换newId –

相关问题