M
Mick Walker
Hi all,
I use the following logic to insert a new record to my database:
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
conn.ConnectionString = ConnString;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.BlogPosts_Insert";
cmd.Parameters.AddWithValue("@Title", Title);
cmd.Parameters.AddWithValue("@BlogContent", Content);
cmd.Parameters.AddWithValue("@DatePosted", DatePosted);
cmd.Parameters.AddWithValue("@NoViews", 0);
cmd.Parameters.AddWithValue("@Category", Category);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new InvalidDataException(ex.Message);
}
finally
{
conn.Close();
cmd.Dispose();
}
This works fine. But I want the function to return the scope identity of
the newly inserted record.
My stored proceedure is as follows:
CREATE PROCEDURE [dbo].[BlogPosts_Insert]
-- Add the parameters for the stored procedure here
@Title varchar(200),
@BlogContent text,
@DatePosted datetime,
@NoViews int,
@Category int
AS
BEGIN
Insert into dbo.BlogPosts (
Title,
BlogContent,
DatePosted,
NoViews,
Category
)
Values (
@Title,
@BlogContent,
@DatePosted,
@NoViews,
@Category
)
select scope_identity()
END
Does anyone know how I can return the ID of the newly inserted item.
Kind Regards
Mick
I use the following logic to insert a new record to my database:
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
conn.ConnectionString = ConnString;
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.BlogPosts_Insert";
cmd.Parameters.AddWithValue("@Title", Title);
cmd.Parameters.AddWithValue("@BlogContent", Content);
cmd.Parameters.AddWithValue("@DatePosted", DatePosted);
cmd.Parameters.AddWithValue("@NoViews", 0);
cmd.Parameters.AddWithValue("@Category", Category);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new InvalidDataException(ex.Message);
}
finally
{
conn.Close();
cmd.Dispose();
}
This works fine. But I want the function to return the scope identity of
the newly inserted record.
My stored proceedure is as follows:
CREATE PROCEDURE [dbo].[BlogPosts_Insert]
-- Add the parameters for the stored procedure here
@Title varchar(200),
@BlogContent text,
@DatePosted datetime,
@NoViews int,
@Category int
AS
BEGIN
Insert into dbo.BlogPosts (
Title,
BlogContent,
DatePosted,
NoViews,
Category
)
Values (
@Title,
@BlogContent,
@DatePosted,
@NoViews,
@Category
)
select scope_identity()
END
Does anyone know how I can return the ID of the newly inserted item.
Kind Regards
Mick