SQL Query (Find Range On Dates Stored as Strings) - mysql

I am currently working with a database which the dates are stored as strings in the (DD/MM/YYYY) format.
I am currently attempting to find a range of dates i.e. (15/07/2017 - 26/07/2017) which will then populate a weekly list.
The issue I am having it because these values are stored as strings within SQL I am unable to select a range unless I specify the values.
I am wondering are there any SQL Wizards out there who can help me.
Thanks,
Joe

you can use between and str_to_date eg:
select *
from my_table
where str_to_date(my__date_column, '%d/%m/%Y')
between str_to_date('15/07/2017', '%d/%m/%Y')
and str_to_date('26/07/2017', '%d/%m/%Y')

Hello Everyone I amended my answer as the previous one was incorrect and unhelpful to other users. In short I had to change the Dates to be stored as Dates correctly within SQL. In short there was no short cut unfortunately.
This is a the SQL Query which i used (No SQL Injection Protected), I hope this is helpful
"SELECT * FROM placement WHERE ('" + StartDate.ToString("yyyy-MM-dd") + "'
between StartDate and EndDate OR '" + EndDate.ToString("yyyy-MM-dd") + "'
between StartDate and EndDate or StartDate = '" + StartDate.ToString("yyyy-
MM-dd") + "' or EndDate = '" + StartDate.ToString("yyyy-MM-dd") + "' or
StartDate = '" + EndDate.ToString("yyyy-MM-dd") + "' or EndDate = '" +
EndDate.ToString("yyyy-MM-dd") + "') AND YearGroup = '" +
User.IntakeYear.ToString() + "' AND Cohort = '" + User.Cohort.ToString() +
"';";
Thanks For Your Feedback.

Related

Fix date in MySQL

Here's the syntax:
string insert_query = "insert into book_borrow (BookID, MemberID, Date_Borrow, Date_Return) values ('" + BookID + "', '" + MemberID + "', curdate(), dateadd(month,1, getdate()))";
const char* q = insert_query.c_str();
qstate = mysql_query(conn, q);
I have error to query execution Problem! 1305
I want to automatically add return date after current date but I can't get it.
For MySQL, it will be DATE_ADD() not dateadd(), document can be found here.
Also do not trust user input like BookID and MemberID to prevent SQL injection. Try using prepared statements.
Try the below SQL
string insert_query = "insert into book_borrow (BookID, MemberID, Date_Borrow, Date_Return)
values ('" + BookID + "', '" + MemberID + "', CURDATE(), DATE_ADD(CURDATE(), INTERVAL 1 MONTH))";

Trying to insert date time into sql with variables in the query

String query = "insert into course_data
values (null, '"
+ CourseName + "','"
+ SCrsDesrpTemp + "','"
+ CrsDes + "','"
+ crsurl + "','"
+ youtube + "','"
+ sqlStrDate + "','"
+ crsduration + "','"
+ CrsImg + "','"
+ category + "',"
+ "'Open2Study',
'0.00',
'English',
'Yes','"
+ CrsImgUni + "','"
+ "GETDATE()" + "')";
That is my attempt above. I am trying to insert the current date and time into a date-time column but I keep getting syntax error for the query. It says GETDATE() is not the correct datatype for the column date-time.
Try this for Sql Server:-
ALTER TABLE course_data ADD CONSTRAINT
DF_MyTable_Inserted DEFAULT GETDATE() FOR crsduration
GO
This assumes your table is named course_data, the column is crsduration, and the name of the contstraint is to be DF_MyTable_Inserteddb in
If db in MySQL NOW() for get current date time
NOW()//Current date time
CURDATE()//Current date

SSRS with UDF and dynamic SQL

I have an SSRS report with a datasource connecting to Oracle db, that then uses a transparent gateway to pull DB2 data. Due to using date range validation, and to have an optional parameter, I am using a udf to build the sql statement dynamically. This works well...
Public Function getData(FromDate AS DATE, ToDate AS DATE, Plant AS STRING, PartNumber AS STRING, ExtTxnCd AS STRING, DateRangeValid AS STRING) AS STRING
Dim sqlStmt AS STRING = ""
sqlStmt = "SELECT ITEM_NO, TXN_DATE, TXN_TIME, QUANTITY, ITEM_DESC, PLANT_NO, ORDER_NO, INT_TXN_CD, EXT_TXN_CD, AREA||ROW||BIN||SHELF Secondary_Loc FROM TABLEA, TABLEB"
sqlStmt = sqlStmt + " WHERE TXN_DATE >= '" + FromDate + "'"
sqlStmt = sqlStmt + " AND TXN_DATE < '" + ToDate + "'"
sqlStmt = sqlStmt + " AND PLANT_NO = '" + Plant + "'"
IF PartNumber <> Nothing THEN
sqlStmt = sqlStmt + " AND REPLACE(ITEM_NO,' ','') = '" + PartNumber + "'"
END IF
sqlStmt = sqlStmt + " AND EXT_TXN_CD = '" + ExtTxnCd + "'"
sqlStmt = sqlStmt + " AND 'True' = '" + DateRangeValid + "'"
sqlStmt = sqlStmt + " AND A_INT_TXN_CD||A_TXN_DESC_CODE = B_INT_TXN_CD||B_TXN_TYPE_CD ORDER BY TXN_DATE, TXN_TIME"
RETURN sqlStmt
END Function
The issue arises in the requirement to have one of the report parameters (ExtTxnCd) allow multiple values to be selected (I've done so many times, just not yet when building the sql statement dynamically like this). If I were to hardcode it, that condition would look something like...
AND EXT_TXN_CD IN ('ABC123','ABC234','ABC678', 'ABC789')
When I change the parameter property to allow multiple values, and change 2 lines in the function's where clause to:
sqlStmt = sqlStmt + " AND THF_EXT_TXN_CD IN ('" + ExtTxnCd + "'"
sqlStmt = sqlStmt + ") AND 'True' = '" + DateRangeValid + "'"
...and try running the report, I get an error:
'Cannot add multiple value query parameter '#ExtTxnCd' for dataset
'Dataset1' because it is not supported by the data extension.'
Then I changed my dataset query, call to the function, to pass in that parameter value as Join(Parameters!ExtTxnCd.Value,","), and in the dataset parameters, changed that parameter's value to also use the JOIN. Now I don't get the errors, but I get no data returned when expecting data based on the parameters selected.
I believe the issue is that the parameter values ... 'ABC123,ABC234,etc..' is being passed in as comma-separated values but as one long string value, rather than each value being passed in being wrapped in single quotes. How would I build the dynamic sql statement with each value in single quotes?
You need to separate the parameters with quotes. Try Join(Parameters!ExtTxnCd.Value, "','")
This means your string is being built in two places however: the intervening quotes and commas in SSRS and the brackets and outside quotes by your Oracle udf. It would be less confusing to build it all in the one spot, so SSRS becomes:
"('" & Join(Parameters!ExtTxnCd.Value, "','") & "')"
and in the Oracle udf it is simply:
sqlStmt = sqlStmt + " AND THF_EXT_TXN_CD IN " + ExtTxnCd

syntax error during update limt or update top(1) c# & access

I have syntax error in this code
string JSS_connetionString011 = null;
OleDbConnection JSS_connection011;
OleDbDataAdapter JSS_oledbAdapter011 = new OleDbDataAdapter();
string JSS_sql011 = null;
JSS_connetionString011 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|/je_salestoredb.mdb;Persist Security Info=True;Jet OLEDB:Database Password=JEPTUSJSSJes";
JSS_connection011 = new OleDbConnection(JSS_connetionString011);
JSS_sql011 = "update product set Siv_Sales_Invoice_NO = '" + textBox1.Text + "' , prod_Status = '" + JSS_product_Status + "' , prod_SALED_ftrCalc = '" + textBox10.Text + "' , piv_SALED_DATE = '" + dateTimePicker1.Text + "' , sivd_ID = '" + textBox3.Text + "' , prod_ROOM ='" + JSS_product_Warhousee + "' where( prod_COMPANY = '" + comboBox4.Text + "' and prod_MODEL = '" + comboBox5.Text + "' and prod_Status = '" + JSS_Ready_For_Sale + "' ORDER BY prod_COMPANY LIMIT 1 )";
JSS_connection011.Open();
JSS_oledbAdapter011.UpdateCommand = JSS_connection011.CreateCommand();
JSS_oledbAdapter011.UpdateCommand.CommandText = JSS_sql011;
JSS_oledbAdapter011.UpdateCommand.ExecuteNonQuery();
Syntax error (missing operator) in query expression '( prod_COMPANY = 'NSN' and prod_MODEL = '606' and prod_Status = 'true' ORDER BY prod_COMPANY LIMIT 1 )'.
There are many records with the same conditions of the query sentence, but each of them have different id.
Any Ideas?
Okay, a couple of things:
One, you can't use ORDER BY or LIMIT in an UPDATE statement in an Access database. The example you linked to is for MySQL, a different database.
Two: What Jon Skeet says is absolutely true: you need to use parameterized SQL rather than putting values directly in SQL.
Three: Given that ORDER BY and LIMIT are not valid in Access update statements, if you replace this bit of code:
+ JSS_Ready_For_Sale + "' ORDER BY prod_COMPANY LIMIT 1 )";
... with this:
+ JSS_Ready_For_Sale + "')";
... the syntax error, or at least that syntax error, may go away.
You might also want to be put a space between the WHERE and the (. I don't know that that will count as a syntax error, but it might.
ETA: ALSO! If you only want to update one record, the one with a specific ID (which I infer from your question text) you will need to specify that record ID in the WHERE clause.
If you records don't have unique IDs, you have a very big problem that you need to fix. A unique ID is absolutely required if you want to be able to update a specific record.
You will also need a properly format string expression for the date:
piv_SALED_DATE = #" + dateTimePicker1.Value.ToString("yyyy'/'MM'/'dd") + "# ,
and in Access SQL you will use "Select Top n .." to select the first n values.

Cannot insert into MySQL via NetBeans

Can someone help me with the problem that I'm having now?
I have a set of question(survey). When the user done the survey, it will insert to my database.
However, right now, when I submit the survey, it doesn't insert the result into my database.
here is my code:
try {
//Process - Query from SQL
String strSqlnsert = "INSERT INTO Customers (MembershipID, Contact, Email, Address, SurveyStatus, Subscription) VALUES"
+ " ('"+ member_ID + "', " + contact_num + ", '" + email_add + "', '" + mail_add + "' , " + radio_group + "," + receive_info + ")";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/customers", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(strSqlnsert);
I've also add in the library for the JDBC in the library folder.
It seems the non numeric values aren't quoted
Instead of
" + email_add + ",
try
'" + email_add + "',
In the below insert statement
INSERT INTO table (field1, field2) VALUES ( 5, 'this is a string');
the 'this is a string' is wrapped in quotes, because field2 is of type VARCHAR. field1 is INT so the value assigned to it (5) doesn't need quoting.
The VALUES list must be in braces too and again, non numeric values must be quoted:
String strSqlnsert = "INSERT INTO Customers (MembershipID, Contact, Email, Address, SurveyStatus, Subscription) VALUES (" + member_ID + ", " + contact_num + ", '" + email_add + "', '" + mail_add + "', '" + radio_group + "', '" + receive_info + "')";
Try to make a prepared statement where you can call setInt or setString method of preparedStatement class . so it will automatically remove string or numeric confusion at all.
BTW preparedStatement is the best way to pass parameter in sql query.don't use Statement class for parameter sql query.