I'm using vb.net 2008 and ADO.NET. When using the ADO CommandBuilder and the Insert Command how can I get the newly created Key? (my Table as an Identity column and this is the key.)
Try your insert command somethign like this
insert into table_name values('first value','second value') set #id = SCOPE_IDENTITY()
And then you can set #id Parameter as below
SqlParameter IDParameter =
new SqlParameter("#id",
SqlDbType.Int);
IDParameter.Direction = ParameterDirection.Output;
insertCommand.Parameters.Add(IDParameter);
Finally you can get the value of id parameter in an int variable
int id = (int)IDParameter.Value;
Related
I can't see where i'm going wrong and was wondering if you could help at all?
Just a basic SELECT with a table.
With regards to the error message, i thought i was declaring the #tableName variable in the parameters section?
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT * FROM #tableName",con);
adapter.SelectCommand.Parameters.Add(new SqlParameter
{
ParameterName = "#tableName",
Value = tableName,
SqlDbType = SqlDbType.NVarChar
});
adapter.Fill(databaseList);
You cannot pass table names to SELECT as a parameter. Construct your SQL dynamically, by inserting the properly quoted (escaped) table name in the SQL string.
From clause not be expression so, cant send parameter
Try this
SqlDataAdapter adapter = new SqlDataAdapter(string.Format("Select * From {0}", "yourTableName"), con);
I have a stored procedure which has to return a bigint as output. below if the definition.
In the body, I'm inserting a row in a table and returning the identity using ##Identity in #LogID output variable.
Everything works except the return part. I have tried casting, converting, selecting and setting the #LogID to ##identity but no luck.
The stored proc is called by enterprise library's Logging block. I'm using Write method of Logwriter class. This is a standard class provided by Microsoft and we have not modified it. I can't show you the code which calls the procedure as this is a DLL and don't have the source code. Anyway, I'm pretty sure it's not the C# code as I get a SQLException so it is something in the sql. The code below is for brevity and there are lots of other columns which I have removed.They are all provided as input parameters.
I'm sure it's a stupid thing, but I'm somehow missing it.
CREATE PROCEDURE [dbo].[WriteLog]
(
#EventID int,
#Priority int,
#LogId bigint OUTPUT
)
INSERT INTO [Log] (EventID, Priority)
VALUES(#EventID,#Priority)
SET #LogID = ##identity
Go
Stored procedures can only return int. So you will need to use the output parameter.
declare #CapturedLogID bigint;
exec dbo.WriteLog #EventID = 42, #Priority = 1337, #LogID = #CapturedLogID output;
In the above example, after the procedure executes, #CapturedLogID stores the value set within the stored procedure (##identity, which, as others have pointed out, should be changed to scope_identity() immediately).
Edit: From C#, to call the procedure with an out parameter:
using (var cmd = new SqlCommand()) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "dbo.WriteLog";
cmd.Parameters.Add("EventID", SqlDbType.Int).Value = 42;
cmd.Parameters.Add("Priority", SqlDbType.Int).Value = 1337;
cmd.Parameters.Add("LogID", SqlDbType.BigInt).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
long logID = (long)cmd.Parameters["LogID"].Value;
}
Note that I've only included the code for setting up and executing the SqlCommand object.
I am trying to add a new row in oracle and get the ID of the newly inserted row, here is what my code looks like
cmd.CommandText = "insert into table1 (id,col2) values (id_seq.NEXTVAL,'abc') returning id into :new_id";
OracleParameter objParameter = new OracleParameter("new_id", OracleDbType.Varchar2);
objParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add(objParameter);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
newID = objParameter.Value;
What am I doing wrong?
Try by changing the insert query to:
insert into table1 (id,col2) values (id_seq.NEXTVAL,'abc') returning id into new_id
I have a stored procedure that uses several input parameters and insert them into Sql Database. There is a problem with one parameter, #CustomerId, that is truncated (but not always) when inserted into database.
C#:
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustomerId", Convert.ToInt32(customerId));
cmd.Connection = sqlConn;
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();
Sql SP:
#CustomerId int
INSERT INTO dbo.tblOffers
(CustomerId)
VALUES
(#CustomerId)
sql table datatype:
CustomerId int not null
Example: 564276117 truncated to 4276117 (but its not happening all the time, and there are values greater than 560000000 that are inserted properly)
What am I doing wrong? Thanks
Try Parameters.Add() method instead of AddWithValue.
cmd.Parameters.Add("#CustomerId",SqlDbType.Int).Value=CustomerID;
Would you please try as below: using ToInt64
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustomerId", Convert.ToInt64(customerId));
cmd.Connection = sqlConn;
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();
If I have the following list in C# that was loaded from the database
List<User> user = GetUsers(foo);
and it was updated and I want to store those changes in the database what's the best way of doing it using SQL? It should insert the records added to that list, updated the modified records and delete the ones that are not present in the collection.
I'm no using the EntityFramework so I need to do this using SQL.
Copy this list to datatable and set datatable RowStat as (modified,deleted,new)
and update datatable using sqldataadapter
Here's an example that adds or inserts a row. It searches for a row with a specific UserID. If the row exists, it uses update to grant the user a point. If the row does not exist, a new row is created with insert.
var connectionString = "Data Source=myServerAddress;" +
"Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
using (var con = new SqlConnection(connectionString))
{
con.Open();
var com = con.CreateCommand();
com.Parameters.AddWithValue("#UserId", userId);
com.CommandText = #"
if exists (select * from YourTable where UserId = #UserId)
update YourTable set TrollPoints = TrollPoints + 1 where UserId = #UserId
else
insert YourTable (UserId, TrollPoints) values (#UserId, 1)
";
com.ExecuteNonQuery();
}
The use of parameters allows the server to chache the execution plan, and also helps against SQL injection.