I am trying to execute following code for I have hardcoded the date in but it doesn't seem to delete it before I had data mismatch expection.
string myQuery = "DELETE FROM Class WHERE Date=#10/12/2015#;";
I ran the SQL query in Access and it didn't work. So I generated it using the tools avaliable there and it looks like that:
DELETE Class.ClassDate FROM Class WHERE (((Class.ClassDate)=#12/10/2015#));
Instead of:
string myQuery = "DELETE FROM Class WHERE Date=#10/12/2015#;";
use
string myQuery = "DELETE FROM Class WHERE Date=#10/12/2015#";
Be sure not to put ; before " in Access SQL in C#
A good reality check is to replace DELETE with SELECT *, if the WHERE clause doesn't return any rows in a SELECT query, it isn't going to delete any either.
Is it possible there is a time component stored in the field Date? The value #10/12/2015# is implicitly #10/12/2015 12:00 AM#, and a test for equality will only return rows that match exactly. If you're actually looking for all rows with any time of day on that date...
WHERE [Date] BETWEEN #10/12/2015# AND #10/12/2015 11:59 PM#
(Not sure if Date is a reserved word in Access -- life is too short to depend on Jet -- but even if it isn't the square brackets won't hurt anything.)
Related
cmd = new SqlCommand("Select Max(Date_Time) From Daily_Sale ", con); cmd.ExecuteNonQuery();
string date_tim = (string)cmd.ExecuteScalar();
MessageBox.Show("date time" + date_tim);
This shows date time in a message box, but when I call this query:
cmdc = new SqlCommand("Select Total_Sale from Daily_Sale Where Date_Time ="+ date_tim,con);
cmdc.ExecuteNonQuery();
I get a syntax error.
Date_Time is saved as nvarchar(50).
First, you need to use parameters to send data to SQL. Never concatenate strings of data to SQL statement. That's a security hole as it's an open door to SQL Injection attacks.
For more information, read How can prepared statements protect from SQL injection attacks? and Microsoft Docs - How to: Perform Parameterized Queries
Second, Never store dates as strings in your database. For date only values, use the Date data type. For time only values, use the Time data type. For date and time values, use the DateTime2 data type (why not use DateTime?).
For more information, read Aaron Bertrand's Bad habits to kick : choosing the wrong data type, and my answer on SO to this question.
Third, you don't need two queries to get the last value of total_sale from the database. You can do that in a single query, without any parameters at all:
SELECT TOP 1 Total_Sale
FROM Daily_Sale
ORDER BY Date_Time DESC
If you want the date time value as well, simply add that to the query:
SELECT TOP 1 Total_Sale, Date_Time
FROM Daily_Sale
ORDER BY Date_Time DESC
I have to remove the particular value from the sentence which is stored in SQL database. Sentence will look like this:
1 Payments:ihj - CHENNAI-HIRE:54005-TN69AZ54008,4021-TN69AZ54005
2 Payments:ihj - CHENNAI-HIRE:54004-TN69AZ54008,4021-TN69AZ54005,54005-TN69AZ54008
In above sentence 54004 is the number which I will pass as parameter to SQL. This is the number which I want to remove from this line but same number is present in this line as TN69AZ54005. This number should not be disturbed, and in another payment we have same amount in another place. Can anyone help on this?
I tried with this sql query
declare #text int=4019
select SUBSTRING(notes,CHARINDEX(cast(#text as varchar),notes),
len(notes)-CHARINDEX(',',notes)+1)
from Accounts.TransactionNotes
where TransactionID=1978
If I use this query it will affect including this line TN69AZ54005
I can see that you've included a C# tag into your question. Then probably the easiest way is just to select all necessary rows using your app, then iterate through them and change the strings to your needs (using eg. PHP preg_replace() equivalent) and update the SQL rows.
I believe that is the easiest way, not really SQL solution but still...
update <table> set notes = replace(notes, 'HIRE:'+ str(<inputparam>),'HIRE:') where transactionid=<transactionid>
update <table> set notes = replace(notes, ','+ str(<inputparam>),',') where transactionid=<transactionid>
You will need to find something to prefix your inputpram value, like in above example I am using "HIRE:" or a comma.
Another way could be to use REGEXP to find the whole word, then one one query would suffice. But I haven't tried it.
The problem here is not the query but the person who designed the
database.
I`m not sure is it this what you want but I will past my code. :)
-- for test create #temp
SELECT
A.DATA
INTO #Temp
FROM
(
SELECT 'Payments:ihj - CHENNAI-HIRE:54005-TN69AZ54008,4021-TN69AZ54005' AS DATA
UNION
SELECT 'Payments:ihj - CHENNAI-HIRE:54004-TN69AZ54008,4021-TN69AZ54005,54005-TN69AZ54008' AS DATA
) AS A
GO
-- this you want?
UPDATE #Temp
SET DATA = REPLACE(DATA,'54004','')
GO
-- select changed data
SELECT * FROM #Temp
I have an insert statement
command.CommandText = " insert into system (ziel, comment, status,art) values (#eort,#comment,#statebox,#Eart) ";
Behind statebox is a Combobox. Every word which can be chosen in the Combobox is created as a tablerow in my database.
the values are created here:
command.Parameters.AddWithValue("#eort",textBo3x.Text);
command.Parameters.AddWithValue("#comment", textBox_Copy1.Text);
command.Parameters.AddWithValue("#statebox", MyComboBox.Text);
command.Parameters.AddWithValue("#Eart", MyComboBox_Copy1.Text);
command.Parameters.AddWithValue("#thetime", thetime_insert.Text);
This works.
But I want to use the #values in the insert Statement like this:
command.CommandText = " insert into els (ziel, #statebox,comment,status,Eart) values (#eort,#thetime,#comment,#statebox,#Eart) ";
This gives me an mysql error.
It seems that the #values have '' at the words.
How can i delete this?
Your INSERT statement as pointed below is wrong. You can't simply plug-in a dynamic column in your insert statement which doesn't exists in your table schema
insert into system (ziel, #statebox,comment,status,Eart)
This can only be done in case of SELECT statement and doing below is perfectly alright
select ziel, #statebox,comment,status,Eart from `system`
Well, if you have your column name in variable then build your query string like
string query = string.Format("insert into els (ziel, {0},comment,status,Eart) values ", column_name_variable);
You cannot use a parameter to reference a field name. However, if you provide your user with a predetermined list of fields between he/she can choose then you can safely use a form of string concatenation to insert the field to update/insert into.
This means that you need to have a combobox without any editing capability but just a selection of the possible fields.
In your case, it seems that this combobox could be the one named MyComboBox
Thus
command.CommandText = #"insert into els
(ziel, " + MyComboBox.SelectedItem.ToString() +
#",comment,status,Eart) values
(#eort,#thetime,#comment,#statebox,#Eart)";
Said that consider to remove the use of AddWithValue. This shortcuts has big drawbacks, in particular when you pass a string variable (Text) and expects it to correctly translate your text in a datetime value.
Use the Add method instead converting and checking your inputs and specifying the correct datetype for the parameter.
DateTime dt;
if(!DateTime.TryParse(thetime_insert.Text, out dt);
// Message, not a valid date....
else
command.Parameters.Add("#thetime", MySqlDbType.Date).Value = dt;
Currently doing a data migration from a Microsoft Access database to a Microsoft SQL Server database using C#. I am trying to create a query to pull data from the Access database and order by two columns: Surname and Date. The challenge is that Date is a string in the following sample format: 12.01.13 (i.e. YY.MM.DD), which is supposed to represent the 13th of January 2012. So I tried the following query in Access:
SELECT * FROM [Contacts 2012]
order by Surname, CDate(Format(Date, "0000-00-00"));
However, I receive this error:
Data type mismatch in criteria expression
So I figure I am getting close. I tried a few different formats, plus maybe DateValue, but to be honest I can't remember. I have looked at other posts both in and outside of stackoverflow, but to no avail.
You said your dates are strings in YY.MM.DD format. If that is correct for all the stored [Date] values ... which means Len([Date]) = 8 for all rows ... those values will sort in the same order whether you sort them as text or transform them to Date/Time values.
So I'll suggest this query ...
SELECT *
FROM [Contacts 2012]
ORDER BY Surname, [Date];
If that returns what you want, you can avoid the data type error you're getting when attempting to transform the strings to actual dates. Also, with an index on the [Date] column, the query will execute significantly faster.
Note this approach is not suitable if some of your [Date] values are not in YY.MM.DD format, eg "12.1.13".
Use Regex.Replace for date format and Regex.Split to add 2 digits to year.
Unsure how i actually finally resolved this but if memory serves i actually sorted the database manually by opening the database in access naturally and sorted by the surname column alphabetically and then sorted by the date column either manually or through a select statement.
here is my query:
select reporttime, datapath, finalconc, instrument from batchinfo
join qvalues on batchinfo.rowid=qvalues.rowid where qvalues.rowid
in (select rowid from batchinfo where instrument LIKE '%TF1%' and reporttime
like '10/%/2010%') and compound='ETG' and name='QC1'
i am running it like this:
// Create a database connection object using the connection string
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
// Create a database command on the connection using query
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
it does not return any results.
when i try this same query in sql server GUI it returns lots of rows
is there a problem specifically with the syntax of the query for c#?
please note that if i simplify the query like select * from table, there is no issue
Can you try using SqlCommand instead of OleDbCommand?
According to MSDN it: Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database.
So if you really are using SQL Server 2008 you should probably use this. Any reason you are not?
How are you setting up the mySelectQuery string?
Could this be a problem with an escape character?
If you're not doing it already,
string mySelectQuery = #"query text here";
Personally I would run query profiler to see what query (if any) is being run, and then go from there.
Are you sure you are connecting to the same database in your code?
On a side note do you need the inner select? Couldn't you write this query as follows.
select reporttime,
datapath,
finalconc,
instrument
from batchinfo
join qvalues on batchinfo.rowid = qvalues.rowid
where compound = 'ETG'
and name = 'QC1'
and batchinfo.instrument like '%TF1%'
and batchinfo.reporttime like '10/%/2010%'
Edit - Never mind, just read the comment that your date is in a varchar field. Will leave this here since it may still be useful information.
Try this:
reporttime like 'Oct%2010%'
I have a test table here and when I query it using
where LastModified like '11/%/2010%'
no rows are returned, although all of the rows in the table have dates in November 2010. When I run the same query using like 'Nov%2010%', it returns all rows.
Details can be found here:
The LIKE clause can also be used to search for particular dates, as well. You need to remember that the LIKE clause is used to search character strings. Because of this the value which you are searching for will need to be represented in the format of an alphabetic date. The correct format to use is: MON DD YYYY HH:MM:SS.MMMAM, where MON is the month abbreviation, DD is the day, YYYY is the year, HH is hours, MM is minutes, SS is seconds, and MMM is milliseconds, and AM designates either AM or PM.