How to define variables in select statement vb.net? - sql

I have a query like this
Dim view_src_14 As String = GetParameterValue("ViewSrc14")
Dim calendar_date_14 As String = GetParameterValue("CalendarDate14")
select calendar_date,view_src,sum(effective) effective_total, sum(ineffective) ineffective_total
from wrk_alert_effectiveness
where calendar_date='" + calendar_date_14 + "' and '" + view_src_14 + "'
group by 1,2
order by 1 desc;
calender_date_14 and view_src_14 are variables... when I run the query it bring this error:
invalid input syntax for type date: ""
Where do i make the changes??

I don't think this is specific enough for an answer, but it is too long for a comment.
You are trying to execute a SQL statement where you pass in values for constants in the statement. This is allowed and a part of SQL -- using parameters. There are two types of parameters, named parameters and positional parameters.
select calendar_date, view_src,
sum(effective) as effective_total, sum(ineffective) as ineffective_total
from wrk_alert_effectiveness
where calendar_date = #date1 and #date2
group by 1, 2
order by 1 desc;
Often, these are represented by ? for anonymous parameters. Sometimes named ones are introduced with colons.
The exact syntax depends on your database and the application interface you are using. My point is that you should learn about parameters and how to use them.

"select calendar_date, view_src, sum(effective) effective_total,
sum(ineffective) ineffective_total
from wrk_alert_effectiveness
where calendar_date= '" + #CalendarDate + "' AND " + #ViewSrc + "
group by 1,2
order by 1 desc;"

Related

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.

Select a record with the largest sum of fields (Access 2010)

I would like to select a record from a table based on the field “labcode” specified by the user on a form. There could be multiple records associated with each “labcode” and I would like to select a record that has the highest sum of 10 corresponding fields in the “tblDSA". Fields are named as follows: “A1_MFI”, “A2_MFI”, “C1_MFI”, "C2_MFI", "DR1_MFI", "DR2_MFI"…)
All 10 fields are in 'text' format and sometimes contains a number, text or are left blank. I would only like to sum up records that contain a number in that field. Do I need to create a new field in “tblDSA” that holds the total score or should I avoid storing calculating values in the table?
Dim SQL As String
Dim db As DAO.Database
Dim tblDSA As DAO.Recordset
Set db = CurrentDb
Set tblDSA = db.OpenRecordset("tblDSA")
SQL = "SELECT * Nz((Val[A1_MFI])) + Nz((Val[A2_MFI])) + Nz((Val[B1_MFI])) + Nz((Val[B2_MFI])) + Nz((Val[C1_MFI])) + Nz((Val[C2_MFI])) + Nz((Val[DR1_MFI]))+ Nz((Val[DR2_MFI])) + Nz((Val[DQB1_MFI] + Nz((Val[DQB2_MFI]))as TotalScore FROM tblDSA WHERE [LABCODE] = " & Me.tbLabcode.Value & " ORDER BY TotalScore DESC "
Debug.Print SQL
Set rs = db.OpenRecordset(SQL)
The SQL above contains a syntax error (missing operator), therefore, I can't test it. I'm not sure what is missing?
Nz() is for skipping blank records and Val() is to convert each text field into value. Please let me know if this is a correct approach or I need to do something else? Thanks
Okay, after much back and forth, here is the final result that works for this particular problem:
SELECT TOP 1 *, (Nz(Val(IIf([A1_MFI] Is Null, 0, [A1_MFI]))) + Nz(Val(IIf([A2_MFI] Is Null, 0, [A2_MFI]))) + ...) AS TotalScore
FROM tblDSA
WHERE [LABCODE] = 57
ORDER BY (Nz(Val(IIf([A1_MFI] Is Null, 0, [A1_MFI]))) + Nz(Val(IIf([A2_MFI] Is Null, 0, [A2_MFI]))) + ...) DESC
I thought Access allowed field aliases in the ORDER BY, but it doesn't seem to do that any more, if it did at all.
It looks like you two things
you didn't have a comman after "SELECT *"
missing two brackets in one of your NZ statements
#PhillipXT pointed out the first - and by using his second suggestion, I think the SQL compiler would have pinpointed the missing brackets for you.
Try this with a copy / paste
SQL = "SELECT *, Nz((Val[A1_MFI])) + Nz((Val[A2_MFI])) + Nz((Val[B1_MFI])) + _
Nz((Val[B2_MFI])) + Nz((Val[C1_MFI])) + Nz((Val[C2_MFI])) + Nz((Val[DR1_MFI])) + _
Nz((Val[DR2_MFI])) + Nz((Val[DQB1_MFI])) + Nz((Val[DQB2_MFI])) AS TotalScore _
FROM tblDSA _
WHERE [LABCODE] = " & Me.tbLabcode.Value & _
" ORDER BY TotalScore DESC "

SQL sort order using 'ORDER BY CASE...'

I'm trying to create a sorting function in SQL but I cannot make this thing work. I have really tried to find some similar problem on Stackoverflow but non that seems to solve my problem. I really not an expert on this things so hope that my explanation is understandable.
So case is as follows: I will list out products an on the website I have links for the user to click that decides what will be sorted, ProductName, ProductID and so on. Chosen sort type is collected from a request.querystring and I use CreateParameter to avoid the risk of SQL injections.
Here is the (simplified) SQL:
"SELECT * FROM Product" & _
"ORDER BY CASE ? " & _
"WHEN 'ID' THEN ProductID " & _
"WHEN 'IDART' THEN ArticleNumber " & _
"ELSE ProductName " & _
"END DESC"
objConnProdList.CommandType = 1
SET objParam = objConnProdList.CreateParameter("#strOrder", adVarchar, adParamInput, 10, "%" & request.querystring("OrderBy") & "%")
Using ELSE I will get the error message:
Conversion failed when converting the nvarchar value 'DiningChair' to data type int.
The problem is that you can't mix different data types in a single case. The syntax would be ok if you convert the values to nvarchars, but that doesn't sort them properly.
If you're using dynamic SQL like in the example, just add the lines to order by you actually need. If you have a stored procedure or something like that, it works with separate order by clauses like this:
SELECT * FROM Product
ORDER BY
CASE #xxx WHEN 'ID' then ProductID end,
case #xxx WHEN 'IDART' THEN ArticleNumber end,
ProductName DESC
i think you make it overly complicated.
var sql = "SELECT * FROM Product";
switch (strOrder)
case when "ID":
sql = sql & " ORDER BY ProductID"
break;
case when "IDART":
sql = sql & " ORDER BY ArticleID"
break;
end;
and run it. there is no place for injection as there is no variable you inject.
This is a variation on JamesZ's answer:
with const as (
select ? as xxx
)
SELECT *
FROM const cross join Product
ORDER BY (CASE xxx WHEN 'ID' then ProductID end),
(case xxx WHEN 'IDART' THEN ArticleNumber end),
ProductName DESC

VB.NET 2010 & MS Access 2010 - Conversion from string "" to type 'Double' is not valid

I am new to VB.Net 2010. Here is my problem: I have a query that uses a combo box to fetch many items in tblKBA. All IDs in the MS Access database are integers. The combo box display member and value member is set to the asset and ID of tblProducts.
myQuery = "SELECT id, desc, solution FROM tblKBA WHERE tblKBA.product_id = '" + cmbProducts.SelectedValue + "'"
In addition to getting items from the KBA table, I want to fetch the department details from the department table, possibly done in the same query. I am trying to do it in two separate queries.
myQuery = "select telephone, desc, website from tblDepartments where tblDepartments.product_id = tblProducts.id and tblProducts.id = '" + cmbProducts.SelectedValue + "' "
All help will be appreciated!
Change the '+' to a '&' then the compiler would be happy.
try adding .toString to cmbproducts.selectedvalue or do "tblKBA.product_id.equals(" & cmbProducts.selectedValue.toString & ")"
1.) Don't use string concatenation to build your query. Use parameters.
2.) I am guessing that tblKBA.product_id is a double and not a string, so don't put quotes around it.
myQuery = "SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = ?"
3 things. Test your value before building the select statement. Second, Use .SelectedItem.Value instead of .SelectedValue. Third, protect yourself from sql injection attack. Use parameters, or at the very least check for ' values.
If IsNumeric(cmbProducts.SelectedItem.Value) = False Then
'No valid value
Return
End If
myQuery = String.Format("SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = {0}", cmbProducts.SelectedItem.Value.Replace("'", "''"))

c# Sql between statement

I'm trying to sort customers billings and i need to sort them by different time periods.
What I've been trying is:
(select billing_date from [transaktions]
between '" + start + "' and '" +stop+"' where konto_nr = #konto_nr")
also
(select billing_date from [transaktions] where konto_nr = #konto_nr" between '" + start + "' and '" +stop+"')
start = the starting period of the date
stop = the ending of the period
The error message I'm getting is
Incorrect syntax near the keyword
'between'.
First of all : you should never concatenate together your SQL statement! That's a big big open door for SQL injection attacks....
Second: you need to put your BETWEEN clause into a WHERE clause:
SELECT billing_date
FROM dbo.[transaktions]
WHERE Billing_Date BETWEEN #Start AND #EndDate
AND konto_nr = #konto_nr
Your syntax should be something like
where Transaktions.Billing_Date between StartDate and EndDate
of the obvious respective columns and variable names you are working with. Yes, you referred to the "billing_date" as a selected column, but the WHERE can be testing OTHER columns of criteria so you have to explicitly identify it there too.