2015-10-14 30 views
-2

C#MSSql:我需要找到最大的ID(主键) )在我的表中,获取值并使用它在我的表中插入一个新行。我需要使用datasource1.SelectCommand。我已经尝试过sqlCommand,但没有奏效。 以下是我到目前为止的代码:我需要找到表中最大的ID(prim键),获取值并使用它在我的表中插入一个新行 - 需要使用datasource1.SelectCommand

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Web; 
using System.Windows.Input; 
using System.Data.SqlClient; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace Project 
{ 
    public partial class ListProperty : System.Web.UI.Page 
    { 

     //Other code here (Page_LOad, Dropdown list, etc) 

     protected void OnButtnClick(object sender, EventArgs e) 
     { 
      string sqlProc1 = "SELECT row from PROPERTY ORDER BY Id DESC Limit 1"; 
      //SqlDataAdapter MxID = new SqlDataAdapter(sqlProc1,SqlDataSource1.SqlCacheDependency); 
      //SqlDataSource1.SelectCommand = sqlProc1; 
      //SqlConnection sqlConnection1 = new SqlConnection(); 
      EntityDataSource cmd = new EntityDataSource(); 
      //SqlCommand cmd = new SqlCommand(); 
      Object returnValue; 

      cmd.CommandText = sqlProc1; 
      //cmd.CommandType = System.Data.CommandType.Text; 
      //cmd.Connection = sqlConnection1; 

      //sqlConnection1.Open(); 

      returnValue = cmd.CommandText; 

      //sqlConnection1.Close(); 

      Object MxID = returnValue; 
      MxID.ToString(); 
      int MxIDint = (Int32)MxID + 1; 
      String strMxID = MxIDint.ToString(); 

      sqlProc1 = "INSERT INTO PROPERTY(ID,Property_ID,Type_ID,Coordinates) VALUES(" + strMxID + ",'1','1','0.')"; 
      SqlDataSource1.SelectCommand = sqlProc1; 
      //GridView1.DataBind(); //generates error 
     } 
    } 
} 

请帮忙!

+2

你能定义“没有工作”吗?你没有从第一个命令中获得正确的价值吗?它没有插入?它崩溃了吗?如果是这样,什么是例外。 – sab669

+0

如果您的ID是一个自动递增索引,请尝试使用'SELECT顶级1行来自PROPERTY ORDER BY Id DESC' for'sql-server','Limit'用于'MySQL' – Milen

+1

,那么您不需要这样做。只需插入您的行和没有ID的值,数据库就会自动为您计算出ID。 – Joe

回答

2

使用该SQL查询:

select MAX(id) from PROPERTY; 
1
queryResult = dbContext.Database 
    .SqlQuery<int>("SELECT Max(Id) from PROPERTY ") 
    .Single(); 

检查了这一点更多细节:get a scalar value

0

我用乔的建议做出的ID密钥,自我增值解决了这个。尽管如此,我必须弄清楚自己是如何做到的。我之前尝试过,但我再次尝试,它确实如此。

相关问题