asp.net razor in webmatrix sql methods - sql

is there any problems with the (var query4) coz th aps desn't show me any msg but it can't insert the data into the table concerne
#{
var userId = Request["UserId"];
var Type = Request["type"];
var db = Database.Open("intranet");
if(Type == "delete")
{
var query = "UPDATE Personne SET Demande = 'refuser' WHERE UserId = '" + userId + "'";
db.Execute(query);
var query2 = "DELETE from DemandeConge where UserId = '" + userId + "'";
db.Execute(query2);
}
else if(Type == "accepte")
{
var query = "UPDATE Personne SET Demande = 'accepte' WHERE UserId = '" + userId + "'";
db.Execute(query);
var query2 = "DELETE from DemandeConge where UserId = '" + userId + "'";
db.Execute(query2);
var query4 = "INSERT INTO CongeAccept(UserId,DateDebut,DateFin,TypeConge) SELECT UserId,DateDebutDemande,DateFinDemande,TypeConge FROM DemandeConge WHERE UserId = '" + userId + "'";
db.Execute(query4);
}
}
and whene i make the comment into this code it works as well :
/* var query = "UPDATE Personne SET Demande = 'accepte' WHERE UserId = '" + userId + "'";
db.Execute(query);
var query2 = "DELETE from DemandeConge where UserId = '" + userId + "'";
db.Execute(query2);*/
var query4 = "INSERT INTO CongeAccept(UserId,DateDebut,DateFin,TypeConge) SELECT UserId,DateDebutDemande,DateFinDemande,TypeConge FROM DemandeConge WHERE UserId = '" + userId + "'";
db.Execute(query4);
}

You are deleting everything from DemandeConge relating to the user you want to insert into CongeAccept so when the try the insert query, there is nothing there to insert. Change the order of your statements and use parameters:
#{
var userId = Request["UserId"];
var Type = Request["type"];
var db = Database.Open("intranet");
if(Type == "delete")
{
var query = "UPDATE Personne SET Demande = 'refuser' WHERE UserId = #0";
db.Execute(query, userId);
var query2 = "DELETE from DemandeConge where UserId = #0";
db.Execute(query2, userId);
}
else if(Type == "accepte")
{
var query = "UPDATE Personne SET Demande = 'accepte' WHERE UserId = #0";
db.Execute(query, userId);
var query4 = "INSERT INTO CongeAccept(UserId,DateDebut,DateFin,TypeConge) SELECT UserId,DateDebutDemande,DateFinDemande,TypeConge FROM DemandeConge WHERE UserId = #0";
db.Execute(query4, userId);
var query2 = "DELETE from DemandeConge where UserId = #0";
db.Execute(query2, userId);
}
}

Related

Updating user info but does not update and has no error

I'm trying to update multiple user info but it won't update. I have tried a lot of ways and all of them would execute, but they do not update the data, and yet throw no errors. Am I missing something?
Here is the code:
protected void Update_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
using (var sqlStt = sqlCon.CreateCommand())
{
sqlStt.CommandType = CommandType.Text;
sqlStt.CommandText = "UPDATE USERS SET LAST_NAME = #LAST_NAME, FIRST_NAME = #FIRST_NAME, BIRTHDATE = #BIRTHDATE, PHONE_NUM = #PHONE_NUM, EMAIL = #EMAIL WHERE USERNAME ='" + Session["USERNAME"] + "' ";
sqlStt.Parameters.AddWithValue("#LAST_NAME", Lname.Text);
sqlStt.Parameters.AddWithValue("#FIRST_NAME", Fname.Text);
sqlStt.Parameters.AddWithValue("#BIRTHDATE", Birthdate.Text);
sqlStt.Parameters.AddWithValue("#PHONE_NUM", Phone_num.Text);
sqlStt.Parameters.AddWithValue("#EMAIL", Email.Text);
sqlStt.ExecuteNonQuery();
}
sqlCon.Close();
Display_Info();
Disable_Field();
Notificationtext.Text = "Your account has been updated!";
}
}
void Disable_Field()
{
Lname.Enabled = false;
Fname.Enabled = false;
Birthdate.Enabled = false;
Phone_num.Enabled = false;
Email.Enabled = false;
}
void Display_Info()
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT LAST_NAME, FIRST_NAME, BIRTHDATE, PHONE_NUM, EMAIL FROM USERS WHERE USERNAME ='" + Session["USERNAME"] + "' ", sqlCon);
SqlDataReader reader;
reader = sqlCmd.ExecuteReader();
if (reader.Read())
{
Lname.Text = reader["LAST_NAME"].ToString();
Fname.Text = reader["FIRST_NAME"].ToString();
Birthdate.Text = reader["BIRTHDATE"].ToString();
Phone_num.Text = reader["PHONE_NUM"].ToString();
Email.Text = reader["EMAIL"].ToString();
}
sqlCon.Close();
}
}
I also wanted to display the update to the textbox then disable it. After I click update, the data before it was updated would display instead.

Convert SQL code to linq (LIKE, SELECT)

How can I do the following sql code with linq?
SQL;
SELECT BusinessEntityID, FirstName + ' ' + LastName AS "FullName"
FROM Person WHERE FullName LIKE 'a%'
LINQ;
using(var db= new db_Context)
{
var query = db.Person.Select(q=> q.FirstName + " "+ q=>q.FullName)
}
Searching after concatenate the strings is not a good idea. I recommend the search for firstname and lastname separately
var query = db.Person.Where (t => t.FirstName.StartsWith("a") || t.LastName.StartsWith("a") )
.Select(q=> new { q.BusinessEntityID, Fullname = q.FirstName + " " + q.LastName })
Following code will be helpful to you,
var list1 = db.Person.Where (t => t.FirstName.StartsWith("a"))
.Select(q=> new {
BusinessEntityID = q.BusinessEntityID,
Fullname = q.FirstName + " " + q.LastName
});
Or
var list2 = from psn in db.Person
where psn.FirstName.StartsWith("a")
select new {
BusinessEntityID = psn.BusinessEntityID,
Fullname = psn.FirstName + " " + psn.LastName
};

Oracle vs Oracle ODBC

The following code works fine from within Oracle's SqlPlus (using Oracle 11.2.02.0g) however when I connect with and ODBC connection via C# code, I get told I have an invalid character.
Since the single quote didn't work in SQLplus, I'm assuming the characters that are consider invalid by ODBC are the double quotes. I've tried braces '{' and brackets '[' but still get the same error -> ERROR [HY000][Oracle][ODBC][Ora]ORA-00911:invalid character <-
Any help would be much appreciated. I still don't understand why SQL statements would be interpreted differently because of the connection type.
CREATE USER "AD1\EGRYXU" IDENTIFIED EXTERNALLY;
Error if ran alone that states the username conflicts with another user or role name. It does create the user in the database.
C# Code is below.
private void button1_Click(object sender, EventArgs e)
{
string happy = "";
string sql1 = "";
string sql2 = "";
string sql3 = "";
string sql4 = "";
string column;
int rownum = -1;
bool frst = false;
string dirIni = "\\\\ramxtxss021-f01\\hou_common_013\\globaluser\\";
string fileIni = "add_users.sql";
string transIniFullFileName = Path.Combine(dirIni, fileIni);
System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection();
num_users = (usrdetails.Count > 0);
if (regions && num_users)
{
using (StreamWriter sw = new StreamWriter(transIniFullFileName))
{
for (int y = 0; y < usrdetails.Count; y++)
{
switch(usrdetails[y].add_del.ToUpper())
{
case "A":
sql1 = "CREATE USER \"" + usrdetails[y].userID.ToUpper() + "\" IDENTIFIED EXTERNALLY;";
sql2 = "GRANT EDMROLE TO \"" + usrdetails[y].userID.ToUpper() + "\";";
sql3 = "INSERT INTO MD_SITE_USER VALUES(generate_key(5), (select user_id from MD_SITE_USER where user_name = '" +
usrdetails[y].group + "') , {" + usrdetails[y].userID.ToUpper() + "}, " + usrdetails[y].seclev +
", '" + usrdetails[y].username.ToUpper() + "', 'U', '" + usrdetails[y].isext.ToUpper() + "', 'N');";
sw.WriteLine(sql1);
sw.WriteLine(sql2);
sw.WriteLine(sql3);
break;
case "D":
sql2 = "DELETE MD_SITE_APP_ACTION_OWNER WHERE user_id in (SELECT user_id FROM MD_SITE_USER where user_name = ‘"+ usrdetails[y].userID + "’+ and user_or_group = ‘U’);";
sql3 = "DELETE FROM MD_SITE_USER where user_name = ‘"+ usrdetails[y].userID + "’ and user_or_group = ‘U’;";
sql4 = "DROP USER "+ usrdetails[y].userID + " FROM USERS;";
sw.WriteLine(sql2);
sw.WriteLine(sql3);
sw.WriteLine(sql4);
break;
default:
MessageBox.Show("Add/Delete command argument not recognized for user\r\n" + usrdetails[y].userID + " \r\n Argument -> " + usrdetails[y].add_del);
break;
}
}
sw.Close();
}
for (int x = 0; x < region.Count; x++)
{
OdbcCommand command = new OdbcCommand();
conn.ConnectionString = "Driver={Oracle in OraClient11g_home1};" +
"Dbq=" + region[x].dbname +
";Uid=" + region[x].username + ";Pwd=" + region[x].password + ";";
try
{
string cmdTexts = File.ReadAllText(transIniFullFileName);
conn.Open();
using (conn)
{
command.Connection = conn;
command.CommandText = cmdTexts;
command.ExecuteNonQuery();
OdbcDataReader dr = command.ExecuteReader();
Form6.dataGridView2.AutoGenerateColumns = false;
if (!frst)
{
for (int i = 0; i < dr.FieldCount; i++)
{
column = dr.GetName(i);
Form6.dataGridView2.Columns.Add("col" + i, column);
Form6.dataGridView2.Columns[i].FillWeight = 1;
}
frst = true;
}
rownum++;
dataGridView1.Rows.Add();
dataGridView1.Rows[rownum].Cells[0].Value = "Results for Region -> " + Form5.region[x].dbname;
dataGridView1.Refresh();
while (dr.Read())
{
rownum++;
Form6.dataGridView2.Rows.Add();
for (int i = 0; i < dr.FieldCount; i++)
{
column = dr.GetValue(i).ToString();
Form6.dataGridView2.Rows[rownum].Cells[i].Value = column;
}
}
Form6.dataGridView2.Refresh();
Form6.dataGridView2.Show();
Form6.Show();
}
conn.Close();
Form6.dataGridView2.Refresh();
}
catch (Exception ex)
{
MessageBox.Show("Error Message: " + ex.Message);
}
}
}
else
{
if (!regions)
happy = "Error - You have not selected any regions.\r\n";
else
happy = "Regions are now selected.\r\n";
if (!num_users)
happy = happy + "Error - You have not entered any users.\r\n";
MessageBox.Show(happy);
}
File.Delete(transIniFullFileName);
}
Don't use ";" (semi-colon) in the command text..
The command text within ODBC or ODP should be a command, e.g. not a set of commands, therefore - ";" is not relevant, and is an invalid character.
it appears you are trying to run a script..
if that is your intent, it should be padded with a "begin" and "end" for the code to be able to run:
BEGIN
INSERT...;
DELETE ...;
END;
(refer to http://www.intertech.com/Blog/executing-sql-scripts-with-oracle-odp/ for more info)
Last thing - if you want to run a "create user" (or any other DDL) from within an anonymous block or a procedure you need to run it with "execute immediate" syntax:
BEGIN
execute immediate 'CREATE USER test IDENTIFIED EXTERNALLY';
END;

Search for multiple values in SQL Server as quickly as possible

I have the following sql statement pulling data from a stored view:
foreach (var id in insert_idlist[0])
{
mssql_con.Open();
//top 1 for duplicate removal
//slowdown?
var mssql_select = "SELECT * FROM dbo.export_to_web WHERE SKU = '" + id + "'";
}
I want to rewrite the sql statement to insert all ids into a single query using an IN clause or similar to speed up execution. However I am aware that IN is a relatively slow operation, so I was hoping to get some expert advice on the fastest possible way of retrieving my data.
Speed is my only concern in this question.
Please note that security is not an issue as this application is pulling all it's variables from an internal database with no direct web access.
Updated code:
try
{
//foreach (var id in insert_idlist[0])
//{
mssql_con.Open();
//top 1 for duplicate removal
//slowdown?
//var mssql_select = "SELECT * FROM dbo.export_to_web WHERE SKU = '" + id + "'";
var mssql_select = "SELECT * FROM dbo.export_to_web WHERE SKU IN (" + insert_idlist .Select(x => "'" + x + "'") .Aggregate((x, y) => x + "," + y) + ")";
//var mssql_select = "SELECT * FROM dbo.Book5 WHERE SKU = '"+id+"'";
SqlCommand cmd = new SqlCommand(mssql_select, mssql_con);
cmd.CommandTimeout = 0;
lbl_dev.Text += "teest";
//Create a data reader and Execute the command
try
{
SqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
insert_idlist[1].Add(dataReader["supplier name"] + " " + dataReader["range description"] + " " + dataReader["item description"]);
insert_idlist[3].Add(dataReader["Sale Price"] + "");
insert_idlist[2].Add(dataReader["WebDesc"] + "");
//insert_idlist[3].Add(dataReader["id"] + "");removed
insert_idlist[4].Add(dataReader["WebDimensions"] + "");
insert_idlist[5].Add(dataReader["RRP"] + "");
insert_idlist[6].Add(dataReader["Normal Price"] + "");
insert_idlist[7].Add("482"); //add me
insert_idlist[8].Add(dataReader["ID"] + "");
lbl_dev.Text += dataReader["supplier name"] + " " + dataReader["range description"] + " " + dataReader["item description"];
lbl_dev.Text += mssql_select;
about_to_insert = about_to_insert + 1;
}
lbl_dyn_status.Text = "Record 0 of " + about_to_insert + "updated.";
dataReader.Close();
mssql_con.Close();
}
catch (Exception e)
{
lbl_dev.Text = "" + e.Message;
}
// }
}
catch (Exception e)
{
lbl_dev.Text = "" + e.Message;
}
I want to rewrite the sql statement to insert all ids into a single
query using an IN clause or similiar.
You can use INSERT INTO ... SELECT ... like so:
INSERT INTO ATable(...)
SELECT * FROM dbo.export_to_web WHERE SKU = someid;
Note that: You have to list the columns' names in the INSERT clause to match what is returned by SELECT *.
If you are on 2008 or higher, the best way to do is pass the values into a Table-Valued Parameter. I always point people to a blog post I wrote here for that.
However, IN is not necessarily a slow operation, as long as the field that you are searching is indexed appropriately - and it would almost certainly be faster than the 'connection per item' approach.
The SQL would then be something like:
var mssql_select = "SELECT * FROM dbo.export_to_web WHERE SKU IN (" + insert_idlist
.Select(x => "'" + x + "'")
.Aggregate((x, y) => x + "," + y) + ")";
Disclaimer - that LINQ may not be 100% spot on :)

How to get records from subquery using union in linq

sql = " SELECT * FROM userDetail ";
sql += " WHERE userId IN ";
sql += " (SELECT friendId FROM userFriends ";
sql += " WHERE approvalStatus='True' AND userId=" + userId;
sql += " UNION";
sql += " SELECT userId FROM userFriends ";
sql += " WHERE approvalStatus='True' AND friendId=" + userId + ")";
In LINQ, you could be something like:
var approvedUsers = db.UserFriends.Where(p => p.ApprovalStatus == "True");
var userIds = from p in approvedUsers
where p.UserId == userId || p.FriendId = userId
select p.UserId;
var friendsAndUser = db.UserDetails
.Where(detail => userIds.Contains(detail.UserId));
Alternatively, use a join:
var query = from user in db.UserFriends
where p.ApprovalStatus == "True"
where p.UserId == userId || p.FriendId == userId
join detail in db.UserDetails on user.UserId equals detail.UserId
select detail;
I suspect neither of these would use a union. You could use a union with LINQ, like this:
var approvedUsers = db.UserFriends.Where(p => p.ApprovalStatus == "True");
var userIds = from p in approvedUsers
where p.UserId == userId
select p.UserId;
var friendIds = from p in approvedUsers
where p.FriendId = userId
select p.UserId;
var allIds = userIds.Union(friendIds);
var friendsAndUser = db.UserDetails
.Where(detail => userIds.Contains(detail.UserId));
... but that's a lot of fuss. I'd probably go with the join.