Error When executing a sql statement - sql

When i am trying to execute the following command i get the following output error.
("INSERT INTO Leaves (EmpID,TotalLeavesRemaining,Year)
SELECT EmpID,TotalLeavesRemaining,'" + year + "'
FROM Leaves
WHERE Year = '" + yearbefore + "' ", con)
Additional information: Conversion from string
INSERT INTO Leaves (EmpID,TotalL" to type 'Double' is not valid.
When i run the command directry through the sql management studio the query does its job !

If you really need to concatenate SQL string then convert your year to string or join using & instead of +
("INSERT INTO Leaves (EmpID,TotalLeavesRemaining,Year)
SELECT EmpID,TotalLeavesRemaining,'" + year.ToString + "'
FROM Leaves
WHERE Year = '" + yearbefore.ToString + "' ", con)

If you put single quotes around your year number it makes it a string. But apparently your year column is of type double. (Why? Shouldn't' it be of type int?). Remove the single quotes!
And also use command parameters. This makes it safer, less error prone and also faster, as the SQL-Server can cache the query and reuse it without having to recompile it and to create an execution plan again.
using (var cmd new SqlCommand(#"INSERT INTO Leaves (EmpID, TotalLeavesRemaining, Year)
SELECT EmpID,TotalLeavesRemaining, #year
FROM Leaves
WHERE Year = #yearbefore", con)) {
cmd.Parameters.AddWithValue("#year", 2015);
cmd.Parameters.AddWithValue("#yearbefore", 2014);
...
}
Note that you don't need any quotes around parameters, even for string parameters. They free you from escaping strings, formatting numbers and dates.
If you want to use multiline strings, use verbatim strings introduced with an #. These string literals can span multiple lines and don't interpret the backslash (\) as an escape character. Single quotes can be escaped by double single quotes.

Related

datetime format changes upon oledbCommand.executeNonQuery

i have an sql insert query in my website,which inserts a few strings and ints, and a datetime in "dd/MM/yyyy HH:mm:ss", and until today it worked great. however, from today, for some odd reason, during the executeNonQuery method of the query, the format of the datetime changes to "MM/dd/yyyy HH:mm:ss". i have no clue as for why this is happening, and it is driving me crazy. can anyone please shed some light on why this happens and how i can prevent this change? any help would be appreciated.
the query:
"INSERT INTO Orders(OrderDate,MemberID,CityID,OrderAdress,CreditCardID,OrderStatus)VALUES(#" + o.OrderDate + "#," + o.MemberID + ","+o.CityID+",'" + o.OrderAdress + "',"+o.CreditCardID+",'Not sent')"
o is an object holding all of the data.
Big problem when trying to build a query when concatenating strings. This is a HUGE thing for exposure to SQL-Injection. The best way to do it is with using PARAMETERIZED queries and you can look all over and find them, you probably were just unaware of them.
Basically in your query, you use a "?" as a place-holder for the parameter you want, then add a parameter object with the actual value / data type and the OleDb querying will put it in its place and have proper data type so you don't have to worry about formatting the string from a date in a specific order.
Also, for names, what if you had a person's name of "O'Conner". You have just pre-terminated your query string and would fail otherwise. You would be severely scratching your head.
Having said all that, lets get back to your query, make it a little more readable, and parameterize it...
You refer to ms-access as the database and OleDb which implies you are writing in either C#, or VB, maybe other. I will demonstrate using C#, you could change as needed to your dev language.
using(OleDbConnection connection1 = new OleDbConnection( WhateverYourConnectionString )
{
connection1.Open();
using(OleDbCommand sqlcmd = new OleDbCommand("", connection1))
{
// simplified query and you can see the "?" place-holders
sqlcmd.CommandText =
#"INSERT INTO Orders
( OrderDate,
MemberID,
CityID,
OrderAdress,
CreditCardID,
OrderStatus )
VALUES
( ?,
?,
?,
?,
?,
'Not sent' )";
// Now, add your parameters in the SAME ORDER as the "?" in the query
sqlcmd.Parameters.AddWithValue("parmForDate", o.OrderDate );
sqlcmd.Parameters.AddWithValue("parmForMember", o.MemberID );
sqlcmd.Parameters.AddWithValue("parmForCity", o.CityID );
sqlcmd.Parameters.AddWithValue("parmForAddress", o.OrderAddress );
sqlcmd.Parameters.AddWithValue("parmForCard", o.CreditCardID );
// since the last parameter is fixed, you can put that in explicitly.
// you can similarly put fixed field of other strings, numbers.
// Now you can execute it
sqlcmd.ExecuteNonQuery();
}
connection1.Close()
}
A DateTime value holds no format, but if you wish to concatenate, do force a format on the string expression for the value:
"INSERT INTO Orders(OrderDate,MemberID,CityID,OrderAdress,CreditCardID,OrderStatus) VALUES(#" + o.OrderDate.ToString("yyyy'/'MM'/'dd") + "#," + o.MemberID + "," + o.CityID + ",'" + o.OrderAdress + "'," + o.CreditCardID + ",'Not sent')"
Still, much simpler to use parameters.

Encapsulate string to ignore quotes

Working in SSIS, I want to capture error message and insert in into my table.
Here's my insert statement (as SSIS variable):
INSERT INTO dbo.info_etl (event_start,event_end,object,event,status,affected_rows,comment)
VALUES
(CONVERT(DATETIME,'"+ (DT_WSTR, 20) #[System::StartTime] +"',103),GETDATE(),'AMDB_ETL_sn_Mirror', 'LOAD','FAILURE', 0 ,
'Component: " + #[System::SourceDescription] +
"Error: " + #[System::ErrorDescription] + "')
Unfortunately this insert fails once content of variable #[System::ErrorDescription] contains quotes (") as this breaks the string I am inserting to column comment.
Example; #[System::ErrorDescription] =
Executing the query "RAISERROR ( 'Whoops, an error occurred.',11,1)" failed with the following error: "Whoops, an error occurred.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Is there any smart way of encapsulating portion of string to be treated literally even if contains quotes?
I think the error is in
DATETIME,'"+ (DT_WSTR, 20) #[System::StartTime] +"',103
I think it should be something like this:
Remove:
'"+
and
+"'

how to write int value inside the query passing through asp.net

I am having the following exception when passing the query through executereader:
incorrect syntax near )"...
How do I write the 0 here?
Here's the whole query:
string query = "select distinct BillNumber,PatientName,MobileNo,DueAmount from PaymentView where RequestDate between '" + fromDate.ToString("yyyy-MM-dd") + "' and '" + toDate.ToString("yyyy-MM-dd") + "' and DueAmount>'"+value+"')";
Extra Closing bracket at end of query. Also DueAmount should not be wrap into single quotes remove it.
and DueAmount>'"+value+"')";
------------^
Note : This may lead to SQL Injection attack, My suggestion is use Sql Parameter.

How to convert an string to a Char(20) sql datatype

I am trying to insert a string into a char(20) column in my SQL Server database.
I set the string to be equal to a value and then add it to a parameter
thisstring = "1914"
cmd.Parameters.AddWithValue("#code", thisstring)
However every time I try it ends up looking like this in the database
I need it to look like the 1913, 000000, 000001 ones.
When I try to pad the string with spaces
thisstring= thisstring.PadLeft(20, " ")
or
thisstring = " " & thisstring
I am getting
String or binary data would be truncated
even if the field wasn't 20 characters total
What am I doing wrong?
Edit*** here is the column in SQL Server
http://imgur.com/BbV6VQv
I am not absolutely sure, but I think the problem lies in the AddWithValue.
While convenient this method doesn't allow to specify the exact datatype to pass to the database engine and neither the size of the parameter. It pass always an nvarchar parameter for a C# UNICODE string.
I think you should try with the standard syntax used to build a parameter
Dim p = new SqlParameter("#code", SqlDbType.Char, 20)
p.Value = thisstring.PadLeft(20, " ")
See this very interesting article on MSDN

Ole DB statement runs in Access but not in Visual Studios

I have the following statement and it returns my desired result in Access however in Visual Studio, I receive an error saying "; expected", what could be the problem?
var query = "SELECT Count(*) FROM usersTable WHERE (((usersTable.[uDateCreated]) Between DateAdd("d",-2,Now()) And Now()))";
You need to escape your quotes inside your string:
" .. Between DateAdd(\"d\",-2 .. "
^ ^ escape the quotes
You're using a quotation mark in your query, which is ending the string. Use apostrophes around d instead:
var query = "SELECT Count(*) FROM usersTable WHERE (((usersTable.[uDateCreated]) " & _
"Between DateAdd('d',-2,Now()) And Now()))"
Specifically:
DateAdd('d',-2,Now())
I think your problem is that you have " (quotes) in your string without escaping them. I donut know which language you are using, but for many you escape with \ (backslash), then your string would read DateAdd(\"d\",