-3

It is my function in order to add a row to a table but I don't know how to return the id of it (Thıs Column's name is Group_id)

public Boolean CreateGroup(string Group_Name, string Description, string category, string username)
    {
        Boolean res = false;



        var sql = "INSERT INTO Group ( Group_Name, Description, User_Name) "
        + "VALUES ( @Group_Name, @Description, @User_Name )";

        SqlCommand cmd = new SqlCommand(sql, Connect());

        cmd.Parameters.Add("@Group_Name", SqlDbType.VarChar, 25).Value = Group_Name;
        cmd.Parameters.Add("@User_Name", SqlDbType.VarChar, 15).Value = username;
        cmd.Parameters.Add("@RSS_Description", SqlDbType.VarChar, 1500).Value = Description;

        try
        {


            cmd.ExecuteNonQuery();
            res = true;
            closeConnection();
        }
        catch (Exception)
        {
            res = false;
        }

        return res;

    }
3692
  • 628
  • 2
  • 6
  • 17
leventkalayz
  • 212
  • 2
  • 5
  • 16
  • 1
    possible duplicate of [Best way to get identity of inserted row?](http://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row) – Pondlife Apr 02 '12 at 10:52

3 Answers3

1

Add to your commandtext SELECT SCOPE_IDENTITY();, then call ExecuteScalar and get the result value.

var sql = "INSERT INTO Group ( Group_Name, Description, User_Name) " +
"VALUES ( @Group_Name, @Description, @User_Name ); " +
"SELECT SCOPE_IDENTITY();";
Steve
  • 213,761
  • 22
  • 232
  • 286
1

Change this:

var sql = "INSERT INTO Group ( Group_Name, Description, User_Name) "
        + "VALUES ( @Group_Name, @Description, @User_Name )";

To this:

var sql = "INSERT INTO Group ( Group_Name, Description, User_Name) "
        + "VALUES ( @Group_Name, @Description, @User_Name );"
        "SELECT SCOPE_IDENTITY() AS Group_id;";

And change this:

cmd.ExecuteNonQuery();

To this:

var yourId= cmd.ExecuteScalar()
Arion
  • 31,011
  • 10
  • 70
  • 88
0

You can also use the OUTPUT clause to retrieve inserted values.

Your SQL query could look like this:

INSERT INTO Group ( Group_Name, Description, User_Name)
output inserted.Id
VALUES ( @Group_Name, @Description, @User_Name )

(assuming the PK column is named 'Id' - please adjust the name if otherwise)

If you use this you'll have to use a DataAdapter to get the data that's returned.

The beauty of this is that if you insert more records, all the newly inserted Ids will be returned. Also, you can retrieve more columns (for example: inserted.Description)

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137