Insert ข้อมูลและส่งค่า Primarykey ที่พึ่ง Insert ล่าสุดกลับมาเพื่อนำไปใช้ต่อ โดยใช้ SELECT CAST(scope_identity() AS int ช่วย

ตัวอย่างโค้ด

 #region Add Scholarship
            Database db = DatabaseFactory.CreateDatabase();
            string sql = @"INSERT INTO [Scholarship] (
       [ScholarName]
      ,[ScholarFromID]
      )VALUES(
       @ScholarName
      ,@ScholarFromID
       );SELECT CAST(scope_identity() AS int)";
            DbCommand dbCommand = db.GetSqlStringCommand(sql);
            db.AddInParameter(dbCommand, "ScholarName", DbType.String, ms.ScholarName);
            db.AddInParameter(dbCommand, "ScholarFromID", DbType.Int32, ms.ScholarFromID);
            
            Int32 KEY_ID=(Int32)db.ExecuteScalar(dbCommand);
            #endregion

 

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.