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
Related
I am loading many .csv files into a SQL Server table using SSIS (Visual Studio 2017).
I am using For Each Loop Container. I have two user variables - FileName (string) and RowCnt (int)
I have developed an audit table (dbo.FEfiles) to track each file loaded along with the number of records in each file.
Audit table has two columns:
1) FileName(varchar(20)
2) RowCount(int)
After the setting up of the Data Flow Task inside the For Each Loop Container, I have an Execute SQL Task that connects to my audit table.
In this Execute SQL Task, in the Expression tab, under the SQLStatementSource, I have the following expression to get the file name alone:
"INSERT INTO dbo.FEfiles (FileName) SELECT '" + #[User::Filename] + "' "
This parses correctly when I evaluate the expression, I get:
INSERT INTO dbo.FEfiles (FileName) SELECT 'filename.CSV'
Now, how do I add the variable for the RowCnt, which has integer data type ?
I tried many options such as the one below:
"INSERT INTO dbo.FEfiles (FileName,RowCount) SELECT '" + #[User::Filename] + "', + (DT_WSTR, 12) #[User::RowCnt] "
When I evaluate the expression, I get the following:
INSERT INTO dbo.FEfiles (FileName,RowCount) SELECT 'filename.CSV', + (DT_WSTR, 12) #[User::RowCnt]
I need to instead get this: INSERT INTO dbo.FEfiles (FileName,RowCount) SELECT 'filename.CSV', 0
Can you kindly help me in getting the right expression ?
I even watched this video, but not able to figure out:
https://www.youtube.com/watch?v=Um7tDy9jZRs
Give this a whirl.
"INSERT INTO dbo.FEFiles (FileName,RowCount) VALUES ('" + #[User::Filename] + "'," + (DT_WSTR, 12) #[User::RowCnt] + ")"
Per users comments had to put RowCount into brackets for column name.
"INSERT INTO dbo.FEFiles (FileName,[RowCount]) VALUES ('" + #[User::Filename] + "'," + (DT_WSTR, 12) #[User::RowCnt] + ")"
String parts
"INSERT INTO dbo.FEFiles (FileName,[RowCount]) VALUES ('"
+
#[User::Filename]
+
"',"
+
(DT_WSTR, 12) #[User::RowCnt]
+
")"
I've been teaching myself Access for the past few weeks and have done well using old questions to solve a lot of the programming conundrums I encountered. I have finally hit a wall and cannot make this filter work correctly.
I'm attempting to use multiple comboboxes on a form to filter a report by a number of criteria. It works great when filtering by customer, branch, and date range, but my numerous attempts at getting G/P% range filter added in have been very frustrating.
I'm using vba to concatenate strings coming from the comboboxes to turn them into a filter, but I either get a data type mismatch error or syntax error with the G/P range function. The underlying queries have [G/P%] formatted as a percent, the comboboxes' source are value lists ("0%","5%","10%",etc.), and I was certain to leave out the single quotes to designate the values as numbers and not strings. I've been at it for many hours trying variations on this code and nothing will work. The individual strings seem okay, but combining them into a single filter to use to open the report is where I think the issue is.
I've tried using Format() to make the values percentages; I've tried setting the variables as strings, integers, and long; I've tried moving all the text down to the final string so the G/P variables are only numbers; at this point I'm convinced that the error I've made is something small and easy that I've overlooked, but I am out of ideas.
The truly frustrating thing is I have a similar code on a different part of the form that only filters with customer name and max G/P and it works perfectly!
Public Sub cmdSalesOVFilter_Click()
Dim strBRFilter As String
Dim strCRFilter As String
Dim strFDateField As String
Dim strTDateField As String
Dim strMinGPFilter As String
Dim strMaxGPFilter As String
Dim strSOFilter As String
If IsNull(Me.cboBranchSales.Value) Then
strBRFilter = " AND [BranchName] Like '*'"
Else
strBRFilter = " AND [BranchName] ='" & Me.cboBranchSales.Value & "'"
End If
If IsNull(Me.cboCustSalesOV.Value) Then
strCRFilter = " AND [CustName] Like '*'"
Else
strCRFilter = " AND [CustName] ='" & Me.cboCustSalesOV.Value & "'"
End If
If IsNull(Me.cboSalesOVDateFrom.Value) Then
strFDateField = " AND [OrderDate]>#" & Format("6/1/2016", "Short Date") & "#"
Else
strFDateField = " AND [OrderDate]>=#" & CDate(Me.cboSalesOVDateFrom.Value) & "#"
End If
If IsNull(Me.cboSalesOVDateTo.Value) Then
strTDateField = " AND [OrderDate]<#" & Format("1/1/2505", "Short Date") & "#"
Else
strTDateField = " AND [OrderDate]<=#" & CDate(Me.cboSalesOVDateTo.Value) & "#"
End If
If IsNull(Me.cboSalesOVMinGP.Value) Then
strMinGPFilter = " AND [G/P%]>=-100"
Else
strMinGPFilter = " AND [G/P%]>=" & Me.cboSalesOVMinGP.Value
End If
If IsNull(Me.cboSalesOVMaxGP.Value) Then
strMaxGPFilter = " AND [G/P%]<=100"
Else
strMaxGPFilter = " AND [G/P%]<=" & Me.cboSalesOVMaxGP.Value
End If
strSOFilter = Mid(strCRFilter & strBRFilter & strFDateField & strTDateField & strMinGPFilter & strMaxGPFilter, 6)
Call ReportFilter(strSOFilter)
DoCmd.OpenReport "rptYTDCustInvoices", acViewReport, strSOFilter
With Reports![rptYTDCustInvoices]
.Filter = strSOFilter
.FilterOn = True
End With
End Sub
The format used in the query is of no importance, so 5% will have the value 0.05.
However, a combobox always returns strings, so 5% selected returns "5%".
This you can convert to a number:
TrueValue = Val("5%") / 100
Now, this must be properly concatenated with your SQL, and the only safe method is to use Str:
TrueTextValue = Str(Val("5%") / 100)
Forget this for a moment, because your other conversion are more or less loose:
This should read:
" And [OrderDate] >= #" & Format(CDate(Me.cboSalesOVDateFrom.Value), "yyyy\/mm\/dd") & "#"
A fixed date should either be literal:
" And [OrderDate] > #6/1/2016#" or " And [OrderDate] > #2016/6/1#"
or use DateSerial:
" And [OrderDate] >= #" & Format(DateSerial( 2016, 6, 1), "yyyy\/mm\/dd") & "#"
For the general formatting of value for concatenating, you can take advantage of my CSql function. The in-line comments list typical usage:
' Converts a value of any type to its string representation.
' The function can be concatenated into an SQL expression as is
' without any delimiters or leading/trailing white-space.
'
' Examples:
' SQL = "Select * From TableTest Where [Amount]>" & CSql(12.5) & "And [DueDate]<" & CSql(Date) & ""
' SQL -> Select * From TableTest Where [Amount]> 12.5 And [DueDate]< #2016/01/30 00:00:00#
'
' SQL = "Insert Into TableTest ( [Street] ) Values (" & CSql(" ") & ")"
' SQL -> Insert Into TableTest ( [Street] ) Values ( Null )
'
' Trims text variables for leading/trailing Space and secures single quotes.
' Replaces zero length strings with Null.
' Formats date/time variables as safe string expressions.
' Uses Str to format decimal values to string expressions.
' Returns Null for values that cannot be expressed with a string expression.
'
' 2016-01-30. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function CSql( _
ByVal Value As Variant) _
As String
Const vbLongLong As Integer = 20
Const SqlNull As String = " Null"
Dim Sql As String
Dim LongLong As Integer
#If Win32 Then
LongLong = vbLongLong
#End If
#If Win64 Then
LongLong = VBA.vbLongLong
#End If
Select Case VarType(Value)
Case vbEmpty ' 0 Empty (uninitialized).
Sql = SqlNull
Case vbNull ' 1 Null (no valid data).
Sql = SqlNull
Case vbInteger ' 2 Integer.
Sql = Str(Value)
Case vbLong ' 3 Long integer.
Sql = Str(Value)
Case vbSingle ' 4 Single-precision floating-point number.
Sql = Str(Value)
Case vbDouble ' 5 Double-precision floating-point number.
Sql = Str(Value)
Case vbCurrency ' 6 Currency.
Sql = Str(Value)
Case vbDate ' 7 Date.
Sql = Format(Value, " \#yyyy\/mm\/dd hh\:nn\:ss\#")
Case vbString ' 8 String.
Sql = Replace(Trim(Value), "'", "''")
If Sql = "" Then
Sql = SqlNull
Else
Sql = " '" & Sql & "'"
End If
Case vbObject ' 9 Object.
Sql = SqlNull
Case vbError ' 10 Error.
Sql = SqlNull
Case vbBoolean ' 11 Boolean.
Sql = Str(Abs(Value))
Case vbVariant ' 12 Variant (used only with arrays of variants).
Sql = SqlNull
Case vbDataObject ' 13 A data access object.
Sql = SqlNull
Case vbDecimal ' 14 Decimal.
Sql = Str(Value)
Case vbByte ' 17 Byte.
Sql = Str(Value)
Case LongLong ' 20 LongLong integer (Valid on 64-bit platforms only).
Sql = Str(Value)
Case vbUserDefinedType ' 36 Variants that contain user-defined types.
Sql = SqlNull
Case vbArray ' 8192 Array.
Sql = SqlNull
Case Else ' Should not happen.
Sql = SqlNull
End Select
CSql = Sql & " "
End Function
I'm new to all coding, I'm looking to update a SQL table, using VBA.
There are 4 columns that need to be updated, and then 4 other columns where to put the new data- so they link up to each other for example A and E link. A is where I want the most updated version of the data and E is where you put it in. I have another column where the user will mark an 'x' if they want these columns updated. I've got the beginning all sorted, connecting it to SQL its just the actual update part I'm stuck with...
So where the Upload Indicator is marked with an x then those columns should be updated, if there is no x just leave them as they are.
'SQL update from four check columns from E-H
'Set Value from "Check Column"
'Where UpdateIndicator sht.Cells(Row,15) = "x"
sSQL = "Update [table].[dbo].[]"
Set Check_titles= titles
Set Check_ratings= ratings
Set Check_star= star
Set Check_location= location
Where "Update Indicator" = x
Ive had to change a lot for an example as its confidential, so makes it slightly harder to explain
Sounds like you need to iterate through your cells in excel, and create an update statement for each row. Something like
Dim n As Integer
Dim sql As String
Do Until Cells(n,1) = ""
If Cells(n,5) = "x"
sql = "Update [dbo].[MyTable] SET "
sql = sql + "Check_titles = '" + Cells(n, 2) + "',"
sql = sql + "Check_ratings = '" + Cell(n, 3) + "',"
sql = sql + "Check_star = '" + Cells(n, 4) + "',"
sql = sql + "Check_location = '" + Cells(n, 5) + "'"
sql = sql + " WHERE Id = " + Cells(n,1) 'Assumes unique id in col 1
MyConn.Execute(sql)
End If
Loop
Where MyConn is your MySql connection and n represents the row number and substitute the column numbers for the correct values for the column names.
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.
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.