Incorrect syntax near ','. error - asp.net

I am getting an SQL error when I try to do this:
public static int GetOrderId(decimal totalprice, int userid)
{
string s = "SELECT * from orders where OrderUserId = " + userid + " and OrderTotalPrice = " + totalprice;
cmd = new SqlCommand(s, con);
int temporderid = Convert.ToInt32(cmd.ExecuteScalar());
return temporderid;
}
As far I can see its because it gets OrderTotalPrice back, the format is incompatible. But I cant figure out how to get it in the compatible format.

It's probably formatting totalprice with a comma, like 3,14, where SQL Server expects a dot, like 3.14.
One way to fix that would be to specify InvariantCulture, which uses a dot:
var s = string.Format(
CultureInfo.InvariantCulture,
"SELECT * from orders where OrderUserId = {0} and OrderTotalPrice = {0:0.0}",
42, 3.1415);
This formats the price as 3.1 on any machine.
By the way, it's much nicer to pass the variables as parameters:
var com = new SqlCommand();
com.CommandType = CommandType.Text;
com.CommandText = "SELECT * from orders where OrderUserId = #userid " +
"and OrderTotalPrice = #totalprice";
com.Parameters.AddWithValue("#userid", 42);
com.Parameters.AddWithValue("#totalprice", 3.1415);
var temporderid = com.ExecuteScalar();
Then you don't have to worry about formats because you send the database a double, not a double formatted as a string.

I guess this is because totalprice gets converted to something like 12,35 when you concatenate the query.
Therefore, I'd suggest you use a parametrized query. E.g. like this:
var s = "SELECT * from orders " +
" where OrderUserId = #userid and OrderTotalPrice = #totalprice";
var cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue("userid", userid);
cmd.Parameters.AddWithValue("totalprice", totalprice);
int temporderid = Convert.ToInt32(cmd.ExecuteScalar());

Related

Conversion failed when converting the varchar to data type int: SQL

I am creating a web app in asp.net mvc I have a query which looks like below
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
var p = new DynamicParameters();
p.Add("#SP_RoleId", "7,8,9", dbType: DbType.String, direction: ParameterDirection.Input);
p.Add("#SP_UserId", userId, dbType: DbType.Int32, direction: ParameterDirection.Input);
var obj = conn.Query<PendingKmsRequest>(sql: "SELECT [f].[id] AS [FileId],[fvr].[Id] AS [RequestId], [au].[Name]"
+ ", [fvr].[RequestByUserId], [fvr].[FromDate], [fvr].[ToDate],[f].[Title], [fvr].[Status], [fvr].[StatusRemarks]"
+ "FROM [dbo].[File] AS[f]"
+ "INNER JOIN [dbo].[FileViewRequest] AS [fvr] ON [f].[CurrentFileVersionId] = [fvr].[FileVersionId]"
+ "INNER JOIN [Access].[User] AS [au] ON [fvr].[RequestByUserId] = [au].[Id]"
+ "WHERE ([fvr].[Status] = 'P' OR ([fvr].[Status] = 'A' AND [fvr].[StatusByUserId] = #SP_UserId AND GETDATE() BETWEEN [fvr].[FromDate] AND [fvr].[ToDate]))"
+ "AND (SELECT 1 FROM [Access].[UserRoleMap] WHERE UserId=#SP_UserId AND RoleId IN(#SP_RoleId)) = 1", param: p, commandType: CommandType.Text);
if (obj != null && obj.Count() > 0)
return obj.ToList();
else
return new List<PendingKmsRequest>();
}
NOTE: Role id is always like (7,8,9) and it is int column in the database.
I get this conversion error on this line of code:
WHERE UserId = #SP_UserId AND RoleId IN (#SP_RoleId))
This is the error:
Conversion failed when converting the nvarchar value '7,9,10' to data type int.
How can I prevent this error?
The following line in your question code:
p.Add("#SP_RoleId", "7,8,9", dbType: DbType.String, direction: ParameterDirection.Input);
The value "7,8,9" is string and parameter type DbType.String is string as well.
But, you said this is int in your database. This is mismatch.
Further, your query:
WHERE UserId = #SP_UserId AND RoleId IN (#SP_RoleId))
The query is using IN clause.
Dapper can convert your value for IN clause if pass in an IEnumerable.
Change the line of code as below:
p.Add("#SP_RoleId", new[] {7,8,9}, dbType: DbType.Int32, direction: ParameterDirection.Input);
No need to use convert string in array or any string split() function
If you have comma saperated string then you can check it like below steps,
If you have #SP_RoleId = "7, 8, 9"
You can convert this string as below
#SP_RoleId = ",7,8,9," ( ',' + ltrim(rtrim( #SP_RoleId )) + ',' )
Now use Like to check ,UserId,
Updated code as below,
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
var p = new DynamicParameters();
p.Add("#SP_RoleId", "7,8,9", dbType: DbType.String, direction: ParameterDirection.Input);
p.Add("#SP_UserId", userId, dbType: DbType.Int32, direction: ParameterDirection.Input);
var obj = conn.Query<PendingKmsRequest>(sql: "SELECT [f].[id] AS [FileId],[fvr].[Id] AS [RequestId], [au].[Name]"
+ ", [fvr].[RequestByUserId], [fvr].[FromDate], [fvr].[ToDate],[f].[Title], [fvr].[Status], [fvr].[StatusRemarks]"
+ "FROM [dbo].[File] AS[f]"
+ "INNER JOIN [dbo].[FileViewRequest] AS [fvr] ON [f].[CurrentFileVersionId] = [fvr].[FileVersionId]"
+ "INNER JOIN [Access].[User] AS [au] ON [fvr].[RequestByUserId] = [au].[Id]"
+ "WHERE ([fvr].[Status] = 'P' OR ([fvr].[Status] = 'A' AND [fvr].[StatusByUserId] = #SP_UserId AND GETDATE() BETWEEN [fvr].[FromDate] AND [fvr].[ToDate]))"
+ "AND (SELECT 1 FROM [Access].[UserRoleMap] WHERE ',' + lTrim(rTrim(#SP_RoleId)) + ',' like '%,' + lTrim(rTrim(UserId) + ',%' " // Updated line
+ "AND RoleId IN(#SP_RoleId)) = 1", param: p, commandType: CommandType.Text);
if (obj != null && obj.Count() > 0)
return obj.ToList();
else
return new List<PendingKmsRequest>();
}

error:Must declare the scalar variable "#ID" asp.net & sql server2014

asp.net & sql server 2014 : why this error appearMust declare the scalar variable"#ID" I looked on goggle and I think it has something to do with insert parameters for ID. Then again I read there could be a typo error.
As I am not going to insert ID column manually I think this is why I am having problem(s) and I don't know how to solve this problem. i cant find out what is missing or wrong could you help please
string query = "insert into LegRent(ID, Day, Date, Name, Nationality, relegon, NatID, Name2, Nationality2, relegon2, NatID2, Type, Building, Flat, UseFor, Duration, StartFrom, EndIn, RentValue, OnlyAr, YearPercent, InsuranceValue, OnlyArInsur, Addres2, Addres) values (#ID, #Day, #Date, #Name, #Nationality, #relegon, #NatID, #Name2, #Nationality2, #relegon2, #NatID2, #Type, #Building, #Flat, #UseFor, #Duration, #StartFrom, #EndIn, #RentValue, #OnlyAr, #YearPercent, #InsuranceValue, #OnlyArInsur, #Addres2, #Addres)";
try
{
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=Construction;Integrated Security=SSPI;";
using (OleDbConnection conn2 = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn2))
{
cmd.Parameters.AddWithValue("#ID", idtxt.Text);
cmd.Parameters.AddWithValue("#Day", daytxt.Text);
cmd.Parameters.AddWithValue("#Date", datetxt.Text);
cmd.Parameters.AddWithValue("#Name", namedd.Text);
cmd.Parameters.AddWithValue("#Nationality", ddNati.Text);
cmd.Parameters.AddWithValue("#relegon", ddRelgon.Text);
cmd.Parameters.AddWithValue("#NatID", NatIDtxt.Text);
cmd.Parameters.AddWithValue("#Name2", namedd2.Text);
cmd.Parameters.AddWithValue("#Nationality2", ddNati2.Text);
cmd.Parameters.AddWithValue("#relegon2", ddRelgon2.Text);
cmd.Parameters.AddWithValue("#NatID2", NatIDtxt2.Text);
cmd.Parameters.AddWithValue("#Type", typrdd.Text);
cmd.Parameters.AddWithValue("#Building", buileddd.Text);
cmd.Parameters.AddWithValue("#Flat", flatdd.Text);
cmd.Parameters.AddWithValue("#UseFor", usetxt.Text);
cmd.Parameters.AddWithValue("#Duration", durationtxt.Text);
cmd.Parameters.AddWithValue("#StartFrom", starttxt.Text);
cmd.Parameters.AddWithValue("#EndIn", endtxt.Text);
cmd.Parameters.AddWithValue("#RentValue", vluetxt.Text);
cmd.Parameters.AddWithValue("#OnlyAr", onlytxt.Text);
cmd.Parameters.AddWithValue("#InsuranceValue", insurtxt.Text);
cmd.Parameters.AddWithValue("#OnlyArInsur", insuronlytxt.Text);
cmd.Parameters.AddWithValue("#YearPercent", percenttxt.Text);
cmd.Parameters.AddWithValue("#Addres2", adresstxt2.Text);
cmd.Parameters.AddWithValue("#Addres", adresstxt.Text);
conn2.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
lbl_msg.Text = "تـــم الحفظ";
int rentMonths = 0;
bool isInt = int.TryParse(durationtxt.Text, out rentMonths);
if (isInt)
{
for (int index = 0; index < rentMonths; index++)
{
OleDbCommand insertRentMonths = new OleDbCommand("INSERT INTO [dbo].[AccRentReceipt] ([ReceiptID] ,[ContractID] ,[Name]) VALUES (#ReceiptID ,#ContractID ,#Name)", conn2);
cmd.Parameters.AddWithValue("#ReceiptID", index + 1);
cmd.Parameters.AddWithValue("#ContractID", ID);
cmd.Parameters.AddWithValue("#Name", namedd.Text);
}
}
}
}
}
catch (Exception ex)
{
lbl_msg.Text = "خطــــأ " + ex.Message;
}

Input string was not in a correct format (ASP.NET)

string s1 = DropDownList1.SelectedItem.Text;
string s2 = DropDownList2.SelectedItem.Text;
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text IS'" + s1 + "' ");
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text IS'" + s2 + "' ");
int v1 = Int32.Parse(sql1);
int v2 = Int32.Parse(sql2);
Hi
I am getting error "Input string was not in a correct format" on line:
int v1 = Int32.Parse(sql1);
Of course you are getting an error!
See you are not fetching result from database. Instead you are assigning your query to sql1 and trying to convert it into integer. See below in your code you are actually assigning whole select query to the string sql1.You can try this one :
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text IS'" + s1 + "' ");
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text IS'" + s2 + "' ");
sqlconnection con = new SqlConnection("Blah Blah")
Sqlcommand cmd = new sqlcommand(sql1,con);
con.open();
int v1 = Convert.toint32(cmd.ExecuteScalar());
con.close();
con.Dispose();
Which type you receive when you
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text IS'" + s1 + "' ");
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text IS'" + s2 + "' ");
?
you can do one thing just take column called Group like you have taken in the Usertype.
Take a session variable and capture username in it.Then get the group to which the username belongs. Based on the role redirect the user to his corresponding page.
Session["unmae"]=txtuname.text;
string username=Session["unmae"].Text;
string group=obj.getgroup(username);
if(group=="Admin")
{
Response.Redirect("1.aspx");
}
else if(group=="User")
{
Response.Redirect("2.aspx");
}
else
{
Response.Redirect("error.aspx");
}
Hope this helps.
Happy coding

Why insert statement generates 2 rows?

I dont know why, but when I do an insert statement in my project, its generate 2 indentical rows instead of makeing just one.
why is that ?
this is my code :
if (ListBox.Items.Count != 0)
{
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string arr = "";
for (int i = 0; i < ListBox.Items.Count; i++)
{
arr += ListBox.Items[i] +",";
}
string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID, #Arrayarray);" + "SELECT SCOPE_IDENTITY()";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.Parameters.AddWithValue("Arrayarray", arr);
commandquery.ExecuteNonQuery();
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
con.Close();
Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);
}
You're running it twice, ExecuteNonQuery() and ExecuteScalar(). Get rid of the ExecuteNonQuery().
you do
commandquery.ExecuteNonQuery();
then right after
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
you do execute it twice
and don't forget to check for sql injection in your code...
I'd check two things:
see how many times this statement is executed (try setting a breakpoint to verify that the code is only run once)
see if there are any triggers in the database that might cause an extra record to be inserted
I had the same problem,I handled it this way.not professional but it works:
Dim x As Boolean = True
If x = True Then
here goes your code to insert to database.
End If
x = False

Refuses to make ExecuteNonQuery : Incorrect syntax near '('

Im trying to insert data to my database, and it gives me an error :
Incorrect syntax near '('.
This is my code :
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string sqlqueryString = "INSERT INTO (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID)";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.ExecuteNonQuery();
con.Close();
I run it in debug mode, and its accepting everything until the "ExecuteNonQuery();" line.
anybody has a clue what I did wrong?
Thanks!
you did this:
INSERT INTO (GameID....
but should do this:
INSERT INTO tablename (GameID....
Your INSERT INTO statement is missing the name of the table into which it is supposed to insert.
The syntax of your insert into statement is incorrect as you are not specifying which table you are inserting into.
The correct syntax is
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
See : http://www.w3schools.com/sql/sql_insert.asp for more information

Resources