close
今天需要使用 Store Procedure 新增一筆資料並傳回自動編號的ID,在保哥網站有詳細解
說,在這邊我只使用其中一種方法範例。
資料表
create table test(
ID int IDENTITY(1,1) NOT NULL primary key,
[Desc] nvarchar(50)
)
Store Procedure
Create PROCEDURE TestAdd
(
@Desc nvarchar(50),@ID int OUTPUT
)
AS
INSERT INTO Test([Desc])Values(@Desc)
Select @ID=@@Identity
測試一下 Store Procedure
DECLARE @ID int
exec TestAdd '123',@ID OUTPUT
print @ID
測試結果
下列為簡易 VB.NET 測試程式碼, 且未實際測試過
Dim conn As New SqlConnection(constr)
Dim cmd As New SqlCommand("TestAdd", conn)
cmd.CommandType = CommandType.StoredProcedure
Dim pDesc As New SqlParameter("@Desc", SqlDbType.NVarChar, 50)
pDesc.Value = Desc
cmd.Parameters.Add(pDesc)
' 設定傳回值
Dim pID As New SqlParameter("@ID", SqlDbType.Int)
pID.Direction = ParameterDirection.Output
cmd.Parameters.Add(pID)
conn.Open()
conn.ExecuteNonQuery()
' 印出傳回值
Console.Write(cmd.Parameters("@ID").Value)
conn.close()
全站熱搜
留言列表