2013年6月11日 星期二

ASP.NET 新增資料後立即取得自動編號的ID(1)

ASP.NET 新增資料後立即取得自動編號的ID(1)


C#:
SqlConnection conn = new SqlConnection(ConnectionString);
conn.open();
string strSQL = "Insert Into table1(t1,t2) value(1,2);select @@IDENTITY";
SqlCommand cmd = new SqlCommand(strSQL);
cmd.Connection = conn;
int i = cmd.ExecuteScalar();   //i就是你要的
cmd.Dispose();
conn.close();
conn.Dispose()

VB:
Dim cid As String = ""
Dim conn As SqlConnection
conn = Class1.conn_sql
Dim command As New SqlCommand("INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description);SELECT SCOPE_IDENTITY() ;", conn)
command.Parameters.AddWithValue("@CategoryName", "test")
command.Parameters.AddWithValue("@Description", "abcd")
conn.Open()
cid = command.ExecuteScalar
conn.Close()

沒有留言:

張貼留言