How to code multiple datasets in VB.NET? - vb.net

I have a report where I need the same data, but for four separate date ranges. Currently this data is based on one month, so it's just one dataset. But now I am trying to do this with four separate datasets, where each one is filtered on each of the four date ranges. I setup my WHILE loop to loop thru all four dates. But I'm having trouble now with distinct naming these datasets. Is this the best way to do this? It looks like if I used multiple datatables for one dataset, I'd have to define each datatable column. Here is my current dataset commandstring:
commandstring = "SELECT Batch_Records.Part_Number, Batch_Records.Lot_Number, Batch_Records.Date_Received, " & _
"IsNull([Date_Completed], [Review_Date]) AS CompleteDate, Batch_Records.Error, " & _
"Batch_Records.[Group], Batch_Records.MFG, Batch_Records.MFG2, Batch_Records.QC, Batch_Records.QC2, " & _
"QC_CODES.CODE_DESC " & _
"FROM EXCEL.Batch_Records LEFT JOIN EXCEL.QC_CODES ON Batch_Records.Part_Number = QC_CODES.CODE_ID " & _
"WHERE (Batch_Records.[Group]" & TheGroup & " AND Batch_Records.Date_Received > '" & arrWeekYear(i, j).ToString("d") & "' AND Batch_Records.Date_Received < '" & arrWeekYear(i + 7, j).ToString("d") & "')"

If I understand it correctly, you want 4 ranges in one query:
extend the WHERE (and watch out for the brackets...)
"WHERE (Batch_Records.[Group]" & TheGroup &
" AND (Batch_Records.Date_Received > '" & arrWeekYear(i1, j).ToString("d") & "' AND Batch_Records.Date_Received < '" & arrWeekYear(i1 + 7, j).ToString("d") &
") or (Batch_Records.Date_Received > '" & arrWeekYear(i2, j).ToString("d") & "' AND Batch_Records.Date_Received < '" & arrWeekYear(i2 + 7, j).ToString("d") &
") or (Batch_Records.Date_Received > '" & arrWeekYear(i3, j).ToString("d") & "' AND Batch_Records.Date_Received < '" & arrWeekYear(i3 + 7, j).ToString("d") &
") or (Batch_Records.Date_Received > '" & arrWeekYear(i4, j).ToString("d") & "' AND Batch_Records.Date_Received < '" & arrWeekYear(i4 + 7, j).ToString("d") &
"'))"
Or if you want to have 4 sets of output, create a parameterized query. Run it 4 times just updating the parameter values. Thus you have no naming problems as you have only 1 query.

Related

Write multiple occurences under single cell in SQL for VBA

I am working on SQL for VBA.
Usually, if we have multiple occurrences of the desired condition, each of the occurrences will be written on different cells, like the code below:
"SELECT CPID " & _
"FROM LCOND_LAST " & _
"WHERE WELL ='" & sht1.Cells(i + 3, 8) & "' " & _
"ORDER CPID"
Which will gives output:
Notice that there are 2 cells to write two occurrences.
My question is, can we just write them on single cells only?
Is there any function that allows us to do so?
You can use the DISTINCT as follows:
"SELECT WELL, CPID " & _
"FROM LCOND_LAST " & _
"WHERE WELL ='" & sht1.Cells(i + 3, 8) & "' " & _
"ORDER BY PSWELLCOND_LAST.CPID"
DISTINCT is used to filter duplicate rows
Learn more about DISTINCT from here.
-- Update
You can use the CHR(10) -- newline and aggregate it as follows:
"SELECT LISTAGG(CPID, CHR(10)) WITHIN GROUP (ORDER BY CPID) " & _
"FROM LCOND_LAST " & _
"WHERE WELL ='" & sht1.Cells(i + 3, 8) & "' "

SQL query assistance needed with 'NOT'

I'm working out of VB6 with SQL SERVER 2012. I found myself in a pickle. Basically i have a query that works fine and pulls the necessary data in SQL SERVER, however, I'm having a difficult time translating it to vb6 SQL code. Here's a working query in SQL SERVER...
SELECT 'TotalSum' = SUM(Units)
FROM tblDetail
WHERE MemberID = '117'
AND CAST(SStartD AS DATETIME) >= '4/1/2016'
AND CAST(SStartD AS DATETIME) <= '4/7/2016'
AND Service = 166
AND [CODE] IN('1919')
AND NOT(InvoiceNo = '11880'
AND DtlNo = 2
)
AND NOT(InvoiceNo = '11880'
AND AdjNo = 2
);
So when I try to write it in my vb6 application i do something like
SELECT 'TotalSum' = SUM(Units)
FROM tblDetail
WHERE MemberID = '117'
AND CAST(SStartD AS DATETIME) >= '4/1/2016'
AND CAST(SStartD AS DATETIME) <= '4/7/2016'
AND Service = 166
AND [CODE] IN('1919')
AND (InvoiceNo <> '11880'
AND DtlNo <> 2
)
AND (InvoiceNo <> '11880'
AND AdjNo <> 2
);
However, this is not giving me the same results. Whats happening is in my last two clauses
( InvoiceNo <> '11880' AND DtlNo<> 2) AND (InvoiceNo <> '11880' AND AdjNo <> 2)
When I run them finally in SQL SERVER don't have paranthesis and its absolutely detrimental that the 2 seperate clauses are in paranthesis. Anyone know what I can do? I think my last resort might be to create a store procedure but i don't really want to do that.
EDIT:
g_SQL = "SELECT 'SUM' = SUM(Units) " & _
"FROM tblDetail WHERE " & _
"MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _
"CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _
"CAST(SStartD As DateTime) <= '" & DateAdd("d", -1, EndDate) & "' AND " & _
"Service = 166 AND " & _
"[CODE] IN (‘1919’)) And " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"DtlNo <> " & (InvoiceDtlRS! InvoiceDtlNo, "")) & " AND " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"AdjNo <> " & InvoiceDtlRS! InvoiceDtlNo)
Your translation of NOT(InvoiceNo = '11880' AND DtlNo = 2) to (InvoiceNo <> '11880' AND DtlNo <> 2) is incorrect.
In formal logic, !(A & B) is equivalent to (!A or !B), so it should be:
(InvoiceNo <> '11880' OR DtlNo <> 2)
This is why you're getting different results. However, why not use the original query? There's nothing in VB6 which would prevent it.
EDIT
g_SQL = "SELECT 'SUM' = SUM(Units) " & _
"FROM tblDetail WHERE " & _
"MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _
"CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _
"CAST(SStartD As DateTime) <= '" & DateAdd("d", -1, EndDate) & "' AND " & _
"Service = 166 AND " & _
"[CODE] IN (‘1919’)) And " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"DtlNo <> " & (InvoiceDtlRS! InvoiceDtlNo, "")) & " AND " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"AdjNo <> " & InvoiceDtlRS! InvoiceDtlNo)
You've got a ) in the wrong place twice. Also, the ) on the final live would be a syntax error I think. The last 5 lines should be:
"[CODE] IN (‘1919’) And " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"DtlNo <> " & (InvoiceDtlRS!InvoiceDtlNo, "") & " AND " & _
("InvoiceNo <> " & InvoiceDtlRS!InvoiceHdrNo & " OR " & _
"AdjNo <> " & InvoiceDtlRS!InvoiceDtlNo & ")"
This should work. I'm able to use SQL queries using NOT with ADODB in VB6.
g_SQL = "SELECT 'SUM' = SUM(Units) " & _
"FROM tblDetail WHERE " & _
"MemID = " & udtCDtl.Lines(udtCDtlIdx).MemID & " AND " & _
"CAST(SStartD As DateTime) >= '" & StartDate & "' AND " & _
"CAST(SStartD As DateTime) <= '" & DateAdd("d", -1, EndDate) & "' AND " & _
"Service = 166 AND " & _
"[CODE] IN ('1919')) And " & _
"NOT (InvoiceNo = " & InvoiceDtlRS!InvoiceHdrNo & " AND DtlNo = " & InvoiceDtlRS!InvoiceDtlNo & ") AND " & _
"NOT (InvoiceNo = " & InvoiceDtlRS!InvoiceHdrNo & " AND AdjNo = " & InvoiceDtlRS!InvoiceDtlNo & ")"
While Marc may have given you a query that works, Simon's question is still valid. The only reason your original query wouldn't work is because you munged the quotes. You'll notice that your parentheses by the reference to InvoiceNo are outside the quotes rather than inside them (there are other problems as well, from changing your original query, but I'll leave you to figure those out for yourself). That makes them not part of the quoted string, and instead part of the VB6 expression. Frankly, Marc isn't doing you any favors by providing an alternative SQL query that happens to have all the VB6 syntax correct, while yours does not. The real problem is that you haven't worked out how to put a SQL query into a quoted string carefully enough.
You can't afford that kind of carelessness if you want to be good at what you're doing. I don't say this to be offensive, but to get your attention. By adopting Marc's solution as the correct one, you haven't really solved your problem, because your problem is a mindset that doesn't think about anything except getting something to work. That mindset makes for the worst kind of programmer, the kind that writes terrible code (hundreds of lines of code where it could be done in 10, for example) that makes nightmares for people who have to maintain it later. Don't be one of those people. When you don't know why something isn't working, go to the trouble of figuring out why. You only have to do it once for each problem, and that mindset will stand you well as you continue to develop your skills.
Again, no disrespect intended. I'm just trying to get you to understand how to avoid getting in "pickles" like this one in future. Hopefully, the next time you post a question here, the "pickle" you're in will be more sophisticated. :)
EDIT: I guess I'm not making myself clear enough. The simple rule is that you need to enclose everything in the working SQL query in quoted strings, and replace the literal search values with references to text boxes, fields, or whatever. So:
sql = "SELECT 'TotalSum' = SUM(Units) " & _
"FROM tblDetail " & _
"WHERE MemberID = '" & myVariable & "' " & _
"AND CAST(SStartD AS DATETIME) >= '" & myVariable & "' " & _
"AND CAST(SStartD AS DATETIME) <= '" & myVariable & "' " & _
"AND Service = 166 " & _
"AND [CODE] IN('1919') " & _
"AND NOT(InvoiceNo = '" & myVariable & "' " & _
"AND DtlNo = " & myVariable & _
")" & _
"AND NOT(InvoiceNo = '" & myVariable & "' " & _
"AND AdjNo = " & myVariable & _
");"
Where myVariable is whatever variable reference you want to replace your literal string with. Any examples you've given have errors in placement of double quotes, which is why you aren't getting the result you want, which is presumably a replication of your working SQL query. The reason Marc's works is not because he altered your original query (it doesn't look like he has, except to put it on less lines) but because he placed his quotation marks correctly. The reason your and simon's solutions don't work is because neither of you have. Going back to your original post, the reason that the parentheses fail to show is because you haven't enclosed them in quotes. Marc has.

Date exception in German windows during insert MS access vb.net

I have written an insert query which inserts datetime along with other columns. It works fine for all locations except when
my German client logs in and runs the application it gives him below error. I have formatted the datevalue to yyyy-mm-dd to make
culture independent.
MS access database is stored in a server in US.
German client is running application from Germany.
strDateSubmit = dtpDateSub.Value.ToString("yyyy-MM-dd")
strSaveOSTR = "INSERT INTO " & strOSTR & " ([OSTR #],[OSTR Type],[# of Samples],[RA#],[Customer],[SKF #],[Test Description]," & _
"[TestLength],[TestUnit],[TestLengthDays],[Requestor],[Date Submitted],[Seals Avail],[Fixtures Available],[Peripherals Avail],[PO Avail]," & _
"[Machine Type],[Hours to Process],[Location],[Current Status],[ErrorsPresent],[ContaminType]" & SampleREcvd1 & ", [Emp_ID],[Industry])" & _
" Values ( '" & strOSTRNum & "', '" & cmbOSTRTypes.Text & "', " & intSamples & ", '" & strRA & "', '" & strCustomer & "', '" & strSKFNum & _
"', '" & strTestDescr & "', " & intTestLength & ", '" & strTestUnits & "', '" & txtTestLDays.Text & "', '" & strRequestor & "', #" & strDateSubmit & "#, '" & strSealAvail & _
"', '" & strFixtAvail & "', '" & strPheriAvail & "', '" & strPOAvail & "', '" & strMachineClass & "', " & intHrstoProc & ",'" & g_objProp.Location & _
"', '" & strStatus & "', '" & ErrorsPresent & "', '" & ContaminationType & "'" & SampleREcvd2 & ", '" & emp_id & "', '" & Industry & "')"
Error: Syntaxfehler in Datum in Abfrageausdruck '#01.02.2016'
Do yourself a favor: Scrap the dynamic SQL and use a parameterized query, e.g.,
sampleSQL = "INSERT INTO TableName ([Date Submitted]) VALUES (?)"
Dim cmd = New OleDbCommand(sampleSQL, conn)
cmd.Parameters.AddWithValue("?", dtpDateSub.Value)
cmd.ExecuteNonQuery()
That way you can use the actual DateTime value returned by the DateTimePicker. You don't have to be concerned with locale settings or string formats or any of those aggravations.
You may need a more strict format of the date expression string:
strDateSubmit = dtpDateSub.Value.ToString("yyyy'/'MM'/'dd")
This will always return a date like "2016/02/01" (no dots or dashes), and it will concatenate correctly here:
"', #" & strDateSubmit & "#, '"
as you intend.

String sql is not in correct format insertion fails using vb.net?How

I am new in vb.net i have sqlcommand string as shown
Dim query As [String] = "insert into tblDefProducts( Creation_Date, Product_code,line_item_id , item_name , category_id , subcategory_id , Gender ,LifeType, supplier_id , Acquire_type , Purchase_type , Manufacture_type , Pur_Con_Unit, Pur_Con_factor ,Tax_At_Retail_Price, Sale_Tax ,Average_cost ,Product_group_id,status,Technical_details )
values( " & DateTimePicker2.Value.ToString() & ",'" & PCode_TXT.Text & "','" & LineItem_TXT.Text & "' , '" & PName_TXT.Text & "','" & CategoryM_CMB.Text & "','" & CategoryS_CMB.Text & "','" & ProductGender_TXT.Text & "', '" & ProductLifeT_CMD.Text & "','" & ProductSupplier_CMB.Text & "','" & PAquireType_CMB.Text & "', '" & PPurchaseType_CMB.Text & "','" & PManufacturing_CMB.Text & "','" & PConnUnit_CMB.Text & "' ," & Convert.ToInt32(PConFactory_TXT.Text) & "," & Convert.ToInt32(PSalesTaxPurchase_TXT.Text) & "," & Convert.ToInt32(PSalesTaxSales_TXT.Text) & "," & Convert.ToInt32(PPRICE_TXT.Text) & " , " & PTypeA & " , " & pActive & ",'" & PTechnicalDetail_TXT.Text & "')"
2 Problems
Input string is not in a correct format second insertion of datetime value from datetimepicker1 to database column creation_date have datatype DateTime but datetimepicker gives value #1/1/1900#
also have to parse using sql
Using string contaternation to pass parameters is not a good idea for a number of reasons: Its vulnerable to SQL Injection attacks, more prone to errors and harder to read and maintain.
In you question the problem is likly due to missing '' around some of your values.
Imagine if you only wanted the user to be able to update certain fields in your table but the user typed something like "Hello', ReadOnlyField = 'World" into a text box which you then concaternate into your query. The ReadOnlyField world be updated. With parameters this would be prevented.
If you use parameters instead you don't need to wory about '' as parameters are typed variables and not strings.
You also don't need to convert everything to a string as most .NET primitves has SQL equivalents.
See here for examples and documentation on VB.Net SqlCommand.Parameters
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters%28v=vs.110%29.aspx
If you have a database columns, which is not of type string, int or any other primitive, you should not pass the value without using the ado.net parameter system (you should never!). Because if you use 01.01.2015 instead of System.DateTime, the database has to parse the date from string to datetime/timestamp, which is often cause issues, because the date is not in a structured form and converting fails. In general, never pass parameter with string concation. One additional reason is, that this allows very easy sql injection and is not as stable as using the ado.net parameter system.
One thing that I see is
Dim query As [String] = "insert into tblDefProducts( Creation_Date, Product_code,line_item_id , item_name , category_id , subcategory_id , Gender ,LifeType, supplier_id , Acquire_type , Purchase_type , Manufacture_type , Pur_Con_Unit, Pur_Con_factor ,Tax_At_Retail_Price, Sale_Tax ,Average_cost ,Product_group_id,status,Technical_details )
values( '" & DateTimePicker2.Value.ToString("yyyyMMdd") & "','" & PCode_TXT.Text & "','" & LineItem_TXT.Text & "' , '" & PName_TXT.Text & "','" & CategoryM_CMB.Text & "','" & CategoryS_CMB.Text & "','" & ProductGender_TXT.Text & "', '" & ProductLifeT_CMD.Text & "','" & ProductSupplier_CMB.Text & "','" & PAquireType_CMB.Text & "', '" & PPurchaseType_CMB.Text & "','" & PManufacturing_CMB.Text & "','" & PConnUnit_CMB.Text & "' ," & Convert.ToInt32(PConFactory_TXT.Text) & "," & Convert.ToInt32(PSalesTaxPurchase_TXT.Text) & "," & Convert.ToInt32(PSalesTaxSales_TXT.Text) & "," & Convert.ToInt32(PPRICE_TXT.Text) & " , " & PTypeA & " , " & pActive & ",'" & PTechnicalDetail_TXT.Text & "')"

Using Case Statement as second part of where clause

I have a current sql query I am using in vb.net to get some data returned to a datagridview. I am checking against the year, month and date of the date time picker to get the necessary information returned from the selected table. My query works fine minus the case statement part to check for specific dates. Can anyone help me fix this query or suggest an alternative method?
"SELECT * FROM " & Me.SelectedTable.SelectedItem.ToString & "
WHERE(Datepart(yyyy," & colName & ") BETWEEN '" & Me.DateTimePicker1.Value.Year & "' AND '" & Me.DateTimePicker2.Value.Year & "'
AND Datepart(mm," & colName & ") BETWEEN '" & Me.DateTimePicker1.Value.Month & "' AND '" & Me.DateTimePicker2.Value.Month & "'
AND Datepart(dd," & colName & ") <= " & Me.DateTimePicker1.Value.Day
& " CASE WHEN Datepart(mm," & colName & ")=" & Me.DateTimePicker1.Value.Month & "
THEN Datepart(dd," & colName & ") = " & Me.DateTimePicker1.Value.Day & "
WHEN Datepart(mm," & colName & ")= " & Me.DateTimePicker2.Value.Month
& " Datepart(dd," & colName & ")= " & Me.DateTimePicker2.Value.Day & "
ELSE Datepart(dd," & colName & ") BETWEEN 1 AND 31 END)"
First, your query is open to SQL injection attacks. You need to fix it by parameterizing your query.
Next, you do not need the CASE there: you can express your logic as a composite logical condition.
I changed the query from one that uses a dynamic column name defined by the value of the colName variable to use col for better readability. I also defined parameters for the values that come from various pickers. You will need to set them on your prepared command before querying.
The part of most interest is at the bottom: I rewrote your CASE as a three-part logical condition that evaluates one of three parts based on the settings of #month1 and #month2, which represent the month values from DateTimePicker1 and DateTimePicker2.
SELECT * FROM Table
WHERE (Datepart(yyyy, col) BETWEEN #year1 AND #year2
AND Datepart(mm, col) BETWEEN #month1 AND #month2
AND Datepart(dd, col) <= #day1
AND (
(Datepart(mm, col)=#month1 AND Datepart(dd, col) = #day1)
OR (Datepart(mm, col)=#month2 AND Datepart(dd, col) = #day2)
OR (Datepart(dd, col) BETWEEN 1 AND 31)
)
It looks like you have just forgotten then "THEN" at the end of your second condition.
So, make it:
CASE
WHEN Datepart(mm," & colName & ")=" & Me.DateTimePicker1.Value.Month & " THEN
Datepart(dd," & colName & ") = " & Me.DateTimePicker1.Value.Day & "
WHEN Datepart(mm," & colName & ")= " & Me.DateTimePicker2.Value.Month & " **THEN**
Datepart(dd," & colName & ")= " & Me.DateTimePicker2.Value.Day & "
ELSE Datepart(dd," & colName & ") BETWEEN 1 AND 31
END