Rahman
Rahman

Reputation: 330

How to store Id (primary key) of newly inserted row into a variable using C#

I am trying to get the Id of newly inserted row as below,

INSERT dbo.Users(Username)  
OUTPUT inserted.ID  
VALUES('my new name');

and when I execute this query in SQL Server 2008, it returns the id. My question is how to store this Id in a variable in asp.net C# to use this value further.

Note: I am not using parametrized query.

Upvotes: 1

Views: 1097

Answers (3)

Helmer
Helmer

Reputation: 126

something like:

            try
            {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = null;
            SqlDataReader rdr = null;
            conn.Open();
            cmd = new SqlCommand(sqlsel, conn);
            rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
              var _id = rdr.GetInt(0);
            }
            conn.Close();

             // do something with _id

Upvotes: 0

gjijo
gjijo

Reputation: 1206

DECLARE @inserted TABLE ( id INT NOT NULL);
INSERT dbo.Users(Username)
OUTPUT inserted.ID INTO @inserted 
VALUES('my new name');

SELECT (id)
FROM @inserted

not sure. just check

Upvotes: 0

GrahamHull
GrahamHull

Reputation: 325

use the execuate scalar property for your command

        int NewNameId = (int)sqlCommand.ExecuteScalar();

Upvotes: 2

Related Questions