My problem is I am trying to insert into a table by using 2 where statements in my Sql Code.
My code:
using (SqlConnection conn = new SqlConnection(#"Connection String"))
{
conn.Open();
using (var cmd = new SqlCommand(#"INSERT INTO AssignPlan
(Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId)
Select #Reps, #Sets, #WeightOrTime, #Date,
Members.MemberId From Members Where Members.Username = #Username,
ExerciseDisplay.ExerciseId From ExerciseDisplay
Where ExerciseDisplay.ExerciseName = #Exercise", conn))
{
cmd.Parameters.AddWithValue("#Reps", txtReps.Text);
cmd.Parameters.AddWithValue("#Sets", txtSets.Text);
cmd.Parameters.AddWithValue("#WeightOrTime", txtWeight.Text);
cmd.Parameters.AddWithValue("#Date", txtDate.Text);
cmd.Parameters.AddWithValue("#Username", lblRegistered.Text);
cmd.Parameters.AddWithValue("#Exercise", txtName.Text);
cmd.ExecuteNonQuery();
Response.Redirect("Success.aspx");
}
conn.Close();
Any ideas on how to rephrase my SQL statement? Any help would be greatly appreciated!
Assuming that there's no relationship between Members and ExerciseDisplay you could do a cross-join and filter the results:
using (var cmd = new SqlCommand(
" INSERT INTO AssignPlan " +
" (Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId) " +
" Select " +
" #Reps, #Sets, #WeightOrTime, #Date, Members.MemberId, ExerciseDisplay.ExerciseId " +
" From Members, ExerciseDisplay " +
" Where ExerciseDisplay.ExerciseName = #Exercise " +
" AND Members.Username = #Username ", conn))
or, since you're just pulling one value from each table, a subquery should work as well:
using (var cmd = new SqlCommand(
" INSERT INTO AssignPlan " +
" (Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId) " +
" Select " +
" #Reps, #Sets, #WeightOrTime, #Date, " +
" (SELECT MemberId FROM Members WHERE Username = #Username), " +
" (SELECT ExerciseId FROM ExerciseDisplay WHERE ExerciseName = #Exercise) "
, conn))
But that requires that each subquery only returns one value.
Related
Im trying to insert this test data in my sql database and I'm getting this error: System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'
Any ideas how to solve this?
DateTime date = DateTime.Now;
string test = "{'payload': {'businessName': 'COMPANY1', 'subscriberName': 'JOHN DOE', 'accountNumber': 'CY68005000121234567890123456', 'numberOfRecords': 1," +
"'currentBalance': 4195.5, 'transactions': [{'transactionNumber': 'TR00000000','sequenceNumber': '000','transactionCode': '305','actualDateTime': '201812041624'," +
"'transactionValueDate': '2018-12-04', 'transactionCurrencyCode': 'EUR', 'transactionAmount': -1149.5, 'balance': 4195.5, 'chequeNo': '', 'depositedBy': 'CY68005000121234567890123456'," +
"'customerReference': 'uniqueValue', 'paymentNotes': 'NOTES', 'exchangeRate': 0}]}, 'errors': null}";
trans = JsonConvert.DeserializeObject<HB_transactions>(test);
for (int i=0; i<trans.payload.transactions.Count; i++)
{
string query = "SELECT TransactionId FROM AABankTransTable";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dataReader = cmd.ExecuteReader();
bool exists = false;
while(dataReader.Read())
{
if(dataReader[0].ToString() == trans.payload.transactions[i].transactionNumber)
{
exists = true;
break;
}
}
dataReader.Close();
if (exists) continue;
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES ('" + trans.payload.transactions[i].transactionNumber + "', 'HB', " + args[0] + ", '" + trans.payload.transactions[i].transactionCurrencyCode + "', " +
trans.payload.transactions[i].transactionAmount + ", " + date + ", 0, '" + trans.payload.transactions[i].depositedBy + "', '" +
trans.payload.transactions[i].paymentNotes + "', " + DateTime.Parse(trans.payload.transactions[i].transactionValueDate) + ")";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
Solved by using SQL parameters instead of string concatenation.
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES (#TransID, 'HB', #COMID, #curr, #amount, #dlDate, 0, #depositor, #Details, #TransDate)";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#TransID", trans.payload.transactions[i].transactionNumber);
cmd.Parameters.AddWithValue("#COMID", args[0]);
cmd.Parameters.AddWithValue("#curr", trans.payload.transactions[i].transactionCurrencyCode);
cmd.Parameters.AddWithValue("#amount", trans.payload.transactions[i].transactionAmount);
cmd.Parameters.AddWithValue("#dlDate", date);
cmd.Parameters.AddWithValue("#depositor", trans.payload.transactions[i].depositedBy);
cmd.Parameters.AddWithValue("#Details", trans.payload.transactions[i].paymentNotes);
cmd.Parameters.AddWithValue("#TransDate", DateTime.Parse(trans.payload.transactions[i].transactionValueDate));
cmd.ExecuteNonQuery();
I see 5 records to be inserted, but only 4 are inserted. The last record is not inserted, and I can not figure out why. Copying from one database to the other. First is an access database, the second is a sql server database.
OleDbCommand cmd2 = new OleDbCommand();
OleDbDataReader oledbReader2;
using (cmd2 = new OleDbCommand())
{
query = "SELECT ID, STRAATNAAM, 'NL' AS TAALCODE, PKANCODE, CITY FROM Temp_Unique_Streetnames WHERE TRIM(Temp_Unique_Streetnames.STRAATNAAM) <> '' AND ID > " + lastId.ToString() + " ORDER BY ID";
WriteToFile(query);
cmd2.CommandText = query;
cmd2.CommandType = CommandType.Text;
cmd2.Connection = cn2;
using (oledbReader2 = cmd2.ExecuteReader())
{
while (oledbReader2.Read())
{
try
{
counter += 1;
query = "insert into tblgeo_street ( autoid, street_id, language, country, city, streetname, zip) values (" + counter.ToString() +
" , " + oledbReader2.GetValue(0).ToString() +
" , 'NL', 23, " + oledbReader2.GetValue(4).ToString() +
" , '" + oledbReader2.GetValue(1).ToString().Replace('\'', 'ยด') + "'" +
" , " + oledbReader2.GetValue(3).ToString() + ") ";
OleDbCommand cmd3 = new OleDbCommand(query, cn3);
WriteToFile(query);
cmd3.ExecuteNonQuery();
}
catch (Exception errorException)
{
actionSucceedded = false;
//eventLog1.WriteEntry("Open db threw exception " + errorException.Message);
WriteToFile("insert tblgeo_street threw exception " + errorException.Message);
}
}
}
}
I am new to SQL, I have table with RecordId that is incremented automatically and is primary key. I would like to get RecordId of the row that was inserted into table.
Thanks in advance for help.
myCommand.CommandText = "INSERT INTO " + tableName + " (DateRaised,RaisedBy,WeekNo,Platform,Department,Site,Process, Area,NavErrorNo,RootCauseDescription,Status) " +
"VALUES ('" + currentDate.ToString(format) + "','" +
sender + "'," +
weekNumber + ",'" +
comboBoxPlatform.SelectedItem + "','" +
comboBoxDepartment.SelectedItem + "','" +
comboBoxSite.SelectedItem + "','" +
comboBoxProcess.SelectedItem + "','" +
comboBoxArea.SelectedItem + "','" +
textBoxNavError.Text + "','" +
textBoxIssue.Text + "','Open')";
//int lastInsertedId =
myCommand.ExecuteNonQuery();
lastInsertedId should be int from RecordId in my table.
To do this properly (if this is for SQL Server - you weren't very clear on this), I see two options:
Approach #1 - using SCOPE_IDENTITY
This works well if you're only ever inserting a single row at a time - use something like this:
// set up your query using *PARAMETERS** as you **ALWAYS** should!
// Using SELECT SCOPE_IDENTITY() to get back the newly inserted "Id"
myCommand.CommandText = "INSERT INTO dbo.SomeTable (list-of-columns) " +
"VALUES (#param1, #param2, #param3, ...., #paramN); " +
"SELECT SCOPE_IDENTITY();";
// set up the parameters and theirs values
object result = myCommand.ExecuteScalar();
if (result != null)
{
int lastInsertedId = Convert.ToInt32(result);
}
Approach #2 - using the OUTPUT clause
This works well even if you insert multiple rows at once (typically using a SELECT after the INSERT):
// set up your query using *PARAMETERS** as you **ALWAYS** should!
// Using SELECT SCOPE_IDENTITY() to get back the newly inserted "Id"
myCommand.CommandText = "INSERT INTO dbo.SomeTable (list-of-columns) " +
"OUTPUT Inserted.RecordId " +
"VALUES (#param1, #param2, #param3, ...., #paramN); ";
// set up the parameters and theirs values
object result = myCommand.ExecuteScalar();
if (result != null)
{
int lastInsertedId = Convert.ToInt32(result);
}
First thing this is not a good idea to call direct SQL statement from code it can cause an issue for SQL injection as #Zohar suggested.
You can either user parametrized query or sp.
Inside sp, you can use
SELECT ##IDENTITY AS 'Identity';
after Insert statement, it will return the last auto-incremented value for PK,
then return this value as an output parameter and catch it after .ExecuteNonQuery(); in C# code.
This should do the trick for You
private void SelectLast()
{
string sqlLast = "SELECT TOP(1) RecordId FROM [YourtableName] ORDER BY 1 DESC";
Connection.Open();
using (SqlCommand cmd = new SqlCommand(sqlLast, Connection))
{
cmd.CommandType = CommandType.Text;
{
int insertedID = Convert.ToInt32(cmdAdd.ExecuteScalar());
textBoxID.Text = Convert.ToString(insertedID);
}
Connection.Close();
}
}
Trying to populate a List with the following code:
string sql = ";WITH getUniqueParams AS (" +
"SELECT DISTINCT [a] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [b] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [c] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [d] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [e] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [f] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [g] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [h] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [i] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [j] AS 'param' FROM table " +
"UNION ALL " +
"SELECT DISTINCT [k] AS 'param' FROM table) " +
"SELECT DISTINCT [param] FROM getUniqueParams ORDER BY [param]"; //the result of this statement to be stored in a string
List<string> lUniqueParams = new List<string>();
// set up SQL connection and command
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=db;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand(sqlGetUniqueParams, conn))
{
conn.Open();
// get a SqlDataReader to read multiple rows
using (SqlDataReader rdr = cmd.ExecuteReader()) //getting exception here when debugging
{
// while there are more result rows.....
while (rdr.Read())
{
// grab the 0-index value from the result row
lUniqueParams.Add(rdr.GetString(0));
}
}
conn.Close();
conn.Dispose();
}
Im getting the exception at the following line of code:
using (SqlDataReader rdr = cmd.ExecuteReader())
Is my query not syntactically correct? The query does not perform well, does the rdr only read so long with no results and then give an exception? Am I missing something?
this is working for me please check this: as change table to [table] in your query and also change using (SqlCommand cmd = new SqlCommand(sqlGetUniqueParams, conn)) to using (SqlCommand cmd = new SqlCommand(sql, conn))
string sql = ";WITH getUniqueParams AS (" +
"SELECT DISTINCT [a] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [b] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [c] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [d] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [e] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [f] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [g] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [h] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [i] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [j] AS 'param' FROM [table]" +
"UNION ALL " +
"SELECT DISTINCT [k] AS 'param' FROM [table]) " +
"SELECT DISTINCT [param] FROM getUniqueParams ORDER BY [param]"; //the result of this statement to be stored in a string
List<string> lUniqueParams = new List<string>();
// set up SQL connection and command
using (SqlConnection conn = new SqlConnection(#"Data Source=server;Initial Catalog=db;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
// get a SqlDataReader to read multiple rows
using (SqlDataReader rdr = cmd.ExecuteReader()) //getting exception here when debugging
{
// while there are more result rows.....
while (rdr.Read())
{
// grab the 0-index value from the result row
lUniqueParams.Add(rdr.GetString(0));
}
}
conn.Close();
conn.Dispose();
}
I created a query to insert into two ms access tables at a time in c#. I got the exception
{System.Data.OleDb.OleDbException: Characters found after end of SQL
statement. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult
hr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&
executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior
behavior, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior
behavior, String method) at
System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at
CompanyDetails.Model.CompanyDetailsModel.setCompanyDetailsToDB(CompanyDetailsDataList
_cmpDetailsList) in E:\Project\PBAttendence\ModifyPrivileage\CompanyDetails\Model\CompanyDetailsModel.cs:line
62}
my sample code is given below please solve my problem. sorry for my bad English.
int companyID = _cmpDetailsList[0].CompanyID;
string companyName = _cmpDetailsList[0].CompanyName;
string contactID = _cmpDetailsList[0].ContactID;
string companyAddress = _cmpDetailsList[0].CompanyAddress;
if (companyID == -1)
{
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
else
{
OleDbCommand upcmd = new OleDbCommand("update CompanyDetails set [CompanyName] = '" + companyName + "',[CompanyAddress] = '" + companyAddress + "',[ContactID] = '" + contactID + "' where [CompanyID] = #cmpID;", conn);
conn.Open();
upcmd.Parameters.AddWithValue("#cmpID", companyID);
upcmd.ExecuteNonQuery();
conn.Close();
}
now i split into two insert command but i got the error {System.Data.OleDb.OleDbException: Syntax error. in query expression 'Select [UserID] from UserDetails;
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
OleDbCommand cmd1 = new OleDbCommand("Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity" + ");", conn);
conn.Open();
cmd1.ExecuteNonQuery();
conn.Close();
The problem is this line of code:
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
You have two insert statements in the same OleDbCommand. Try to move this into two different steps:
Insert into CompanyDetails table
Insert into UserCompanyDetails table
Hope this helps you
First of all , it would have been easier with the raw sql command then your code generating the sql.
You might consider making a stored procedure since your command is getting kinda complex
If i'm correct , what you are currently trying to do is :
Insert into table1(x,y,z) values a,b,c;
Insert into table2(x,y) values select * from table3; , ##identity
The second sql command is invalid in both syntax and logic, your ##identity won't be static since you're inserting new records during your command.
My recommendation would be to do something like this :
Insert into table1(x,y,z) values a,b,c;
declare #table1Id int = ##identity
Insert into table2(x,y) select colA, #table1Id from table3;
You cannot have ; in queries in Access. See http://office.microsoft.com/en-us/access-help/HV080760224.aspx You will have to do the two inserts separately as suggested by #juanreyesv
You will have to do 3 queries,
Do the insert using your sql: "Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "')
Get the ##identity using
Select ##identity and store it in a variable say idnt
Use the identity value obtained in 2. to do the third insert:
"Insert into UserCompanyDetails([UserID],[CompanyID])
Select UserID, " + idnt.ToString() + " from UserDetails"
Refer to http://msdn.microsoft.com/en-us/library/ks9f57t0%28VS.71%29.aspx