建立資料表:

CREATE TABLE Test
(
  id int IDENTITY(1,1) NOT NULL,
  name nchar(10) NULL
)

 

程式指令:

SqlCommand cmd = new SqlCommand();

cn.Open();

cmd.Connection = cn;

cmd.CommandText = "Declare @id Int;Insert Into Test(name)Values('a');Select @id=@@Identity;Select @id;";

int i = (int)cmd.ExecuteScalar();

cn.Close();

 


 

SQL指令依照分號;」來分行後,呈現結果如下:

  1   Declare @id Int ;                                         

  2   Insert Into Test ( name ) Values ( 'a' ) ;     

  3   Select @id = @@Identity ;                           

  4   Select @id ;                                                 

  

第一行,宣告一個 Int 型態的變數 @id 

第二行,Insert 資料到 Test 資料表

第三行,取得本次 Insert 指令的 Identity 值,並放入變數 @id

第四行,使用 Select 語法將變數 @id 呈現至畫面,或送至 Client 端 的指令結果中供物件使用

arrow
arrow
    全站熱搜

    Jiang Ying-Fu 發表在 痞客邦 留言(0) 人氣()