using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (#FBUID); SELECT CAST(scope_identity() AS int)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
int lastID = (int)command.ExecuteScalar();
}
Without the
SELECT CAST(scope_identity() AS int)
One row is inserted. But since I need the ID from the created row im using scope_identity. However, when I use this, 2 rows are created instead of one.
Did I miss something?
Thanks
The problem in the code you've posted is that you run 2 times the same query... one with ExecuteNonQuery(); and the last with (int)command.ExecuteScalar();
If you try to use only the executeScalar i think you have the result's you want....
Try and hope this helps...
If you want you can use Parameter to retrieve the Identity, like they do in this Article
If you would use gbn or my answer from your first question, the problem shouldn't occur.
Try doing
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (#FBUID);";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#FBUID", FBUID);
connection.Open();
command.ExecuteNonQuery();
query = "SELECT CAST(scope_identity() AS int)";
command = new SqlCommand(query, connection);
int lastID = (int)command.ExecuteScalar();
}
Related
I want to display the data that is selected in the SQL query , I tried to use ExecuteScalar() but it only work with 1 value , here is my c# code :
SqlConnection conn = new SqlConnection("Data Source=MAX-PC\\SQLEXPRESS;Initial Catalog=newSchool;Integrated Security=True");
SqlCommand cmd = new SqlCommand("view_profile", conn);
cmd.CommandText = "exec view_profile #posted_id";
cmd.Parameters.AddWithValue("#posted_id", WebForm1.x);
conn.Open();
cmd.ExecuteNonQuery;
conn.Close();
and that's the proc :
CREATE PROC view_profile
#posted_in INTEGER
AS
BEGIN
SELECT P.poster , P.post_description
FROM Posts P
WHERE P.posted_in = #posted_in
END
you are a little confused:
ExecuteScalar(): Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
ExecuteNonQuery(): Executes a Transact-SQL statement against the connection and returns the number of rows affected, it is intended for UPDATE, INSERT and DELETE queries
What you need is ExecuteReader()
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
I have two tables, one containing names, and one containing rates and other data that is lined to each name. After I insert a new name into table A, I want to get the newly auto generated PK to now use to insert into my other table B with rates.
How can I do this? I read about scope_identity online but I'm not sure how to use it.
This is what I have so far:
SqlConnection con = new SqlConnection(pubvar.x);
SqlCommand command = con.CreateCommand();
command.CommandText ="Insert into A values('" +Name + "')";
SqlCommand command2 = con.CreateCommand();
command2.CommandText = "Insert into B values(....)";
SELECT SCOPE_IDENTITY();
con.Open();
command.ExecuteNonQuery();
con.Close();
Considering the case you've described, I don't see any need to return the identity from the database. You can simply issue both statements in one command:
using (var cnx = new SqlConnection(pubvar.x))
using (var cmd = new SqlCommand
{
Connection = cnx,
CommandText = #"
insert into A (Name) values (#name)
insert into B (A_ID, Rate) values (scope_identity(), #rate)
",
Parameters =
{
new SqlParameter("#name", name),
new SqlParameter("#rate", .5m) //sample rate
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
I have this stored procedure:
Insert into dbo.file_row (file_sub_type) values (#file_sub_type)
DECLARE #result int;
SET #result = SCOPE_IDENTITY()
RETURN #result;
This works fine to return the id in SSMS. However, when I call it from C#, it returns -1.
var connection = GetSqlConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "InsertInto_file_row";
command.Parameters.Add(new SqlParameter("#file_sub_type", fileType));
int result = command.ExecuteNonQuery();
connection.Close();
return result;
I don't see what I am doing wrong. I just need the Id of the inserted record.
Greg
Check the docs on ExecuteNonQuery():
Executes a Transact-SQL statement against the connection and returns the number of rows affected.
(Emphasis mine)
If you want to get information back, you have a couple options:
Change RETURN to SELECT and ExecuteNonQuery() to ExecuteScalar()
Use an OUTPUT parameter
To add on to Joel's response
Try ExecuteScalar instead
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. (Overrides DbCommand.ExecuteScalar().)
This will help you. The function returns the new Identity column value if a new row was inserted, 0 on failure. It is from MSDN
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
public int AddProductCategory(string newName, string connString)
{
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Name", newName);
con.Open();
latestInsertedId = (int)cmd.ExecuteScalar();
con.Close();
}
return latestInsertedId ;
}
}
i have database in access with auto increase field (ID).
i insert record like this (in C#)
SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') ";
OleDbCommand Cmd = new OleDbCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Conn.Close();
how to get the last inserting number ?
i dont want to run new query i know that in sql there is something like SELECT ##IDENTITY
but i dont know how to use it
thanks in advance
More about this : Getting the identity of the most recently added record
The Jet 4.0 provider supports ##Identity
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
I guess you could even write an extension method for OleDbConnection...
public static int GetLatestAutonumber(
this OleDbConnection connection)
{
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", connection))
{
return (int)command.ExecuteScalar();
}
}
I like more indicate the type of command
is very similar to the good solution provided by Pranay Rana
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql_Insert;
cmd.ExecuteNonQuery();
cmd.CommandText = sql_obtainID;
resultado = (int)comando.ExecuteScalar();
}
query = "Insert Into jobs (jobname,daterecieved,custid) Values ('" & ProjectNAme & "','" & FormatDateTime(Now, DateFormat.ShortDate) & "'," & Me.CustomerID.EditValue & ");"'Select Scope_Identity()"
' Using cn As New SqlConnection(connect)
Using cmd As New OleDb.OleDbCommand(query, cnPTA)
cmd.Parameters.AddWithValue("#CategoryName", OleDb.OleDbType.Integer)
If cnPTA.State = ConnectionState.Closed Then cnPTA.Open()
ID = cmd.ExecuteNonQuery
End Using
Using #Lee.J.Baxter 's method (Which was great as the others id not work for me!) I escaped the Extension Method and just added it inline within the form itself:
OleDbConnection con = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
cmd.Connection = con;
cmd.ExecuteScalar();
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", con))
{
ReturnIDCast =(int)command.ExecuteScalar();
}
NOTE: In most cases you should use Parameters instead of the string.Format() method I used here. I just did so this time as it was quicker and my insertion values are not coming from a user's input so it should be safe.
Simple,
What we do in excel for copy text in above cell?
Yes, just ctrl+" combination,
and yes, it's work in MS ACCESS also.
You can use above key stroke combination for copy above records field text, just make sure if you have duplicate verification applied or edit field data before move next field.
If you aspects some more validation or any extraordinary then keep searching stack overflow.
On my current project, to get a single value (select column from table where id=val), the previous programmer goes through using a datarow, datatable and an sqldatadapter (and of course sqlconnection) just to get that one value.
Is there an easier way to make a simple select query? In php, I can just use mysql_query and then mysql_result and I'm done.
It would be nice if I could just do:
SqlConnection conSql = new SqlConnection(ConnStr);
SomeSqlClass obj = new SomeSqlClass(sql_string, conSql);
conSql.Close();
return obj[0];
Thanks for any tips.
You can skip the DataReader and the DataAdapter and just call ExecuteScalar() on the sql command.
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM whatever
WHERE id = 5", conn);
try
{
conn.Open();
newID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You are probably looking for SqlCommand and SqlDataReader
Dictionary<int, string> users = new Dictionary<int, string>();
using(SqlConnection connection = new SqlConnection("Your connection string"))
{
string query = "SELECT UserId, UserName FROM Users";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
users.Add(reader.GetInt32(0), reader.GetString(1));
}
connection.Close();
}
Actually, there is a method SqlCommand.ExecuteScalar() that will simply return the first field from the first row of the returned results. Just for you.
.NET Framework Class Library
SqlCommand..::.ExecuteScalar Method
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
You can do something very similar:
using (SqlConnection conn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(sql_string, conn))
{
conn.Open();
return cmd.ExecuteScalar();
}
you can use SqlCommands executeScalar function. Please look at the following link
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx