Loading Chinese character to DB2 using SQL Insert statement - sql

I need to use VBA excel macro to load Chinese character data from excel spreadsheet to DB2 using SQL Insert Statement. I know that this cannot work with normal Insert statement as below:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
Since this is my first time dealing with double byte character, can anybody help to guide me on which method I can use to load DBCS data into DB2.
Thanks in advance.

A few things:
Not knowing your table and column names, enclose them with square brackets to be on the safe side
There must be no space between the N' prefix and the Unicode data, nor a space after the value itself
Your data1 value is not enclosed in quotation marks; this means it must be a numeric value. If it is not a numeric value, enclose it in quotation marks. If it is a Unicode string, enclose it in "N'..."'"
Try with this:
oStr = "INSERT INTO [" & tableName & "] ([" & field1 & "], [" & field2 & "]) Values(" & data1 "," & " N'" & data2 & "');"

Related

Use a string (multivalued field from table) as where clause in SQL query

I try to redefine a SQL query with VBA to include the content of a multivalued table field as a where clause but I can't get it to work.
First I gather all the values from the specific multivalued field (formatted as text, can't use numbers due limitations during the import)
BLPN_Query = DLookup("Kostenstellen_Report", "Optionen_Reportgenerierung", "ID=1")
MsgBox will return this (mind the space between ";" and the next text):
34; 44
This string can contain several different text entries. I would like to use the string "BLPN_Query" as a where clause condition. What I've got so far is this:
"WHERE (PROKALK.NK_STK>0) AND (PROKALK.TERMIN>{d '" & Startjahr & "-01-01'}) AND (PROKALK.BLPNR='" & BLPN_Query & "')"
If there is only one entry it works, but in case there are more than one it won't work (obviously). Not sure but I guess the space between the semicolon and the next text is an issue as well as I have to use "IN" instead of "=" but I don't know how to do this.
Solution (thanks to Andre!)
1.) Get data from table (looks like: 34; 35; 36), remove the spaces and replace the semicolon by a comma including single quotes between the elements for the IN clause. Now it looks like: 34','35','36
BLPN_Query = DLookup("Kostenstellen_Report", "Optionen_Reportgenerierung", "ID=1")
BLPN_Query = Replace(BLPN_Query, " ", "")
BLPN_Query = Replace(BLPN_Query, ";", "','")
2.) Include the string within the where clause (and add a single quote before and after the string) --> Final string: '34','35','36'
AND (PROKALK.BLPNR IN ('" & BLPN_Query & "'))"
it's not pretty but will help us until we finally get the new ERP system and can replace all the old stuff
IN (...) expects comma, so you need to do:
BLPN_Query = Replace(BLPN_Query, ";", ",")
and then in the WHERE clause:
"WHERE ... AND (PROKALK.BLPNR IN (" & BLPN_Query & "))"
Extra spaces don't hurt. This also works if BLPN_Query contains a single value, but it doesn't if it is empty.

MS Access / SQL : error in insert query statement

I am using MS Access 1997 version (.mdb file). On a daily basis, I need to insert values manually. In that file, there's a column Logical (Boolean data type). I am automate this template using SQL query instead of direct entry.
Below is my insert query:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Logicalnme & ")
Values:
Logicalnme - True
When I run this query in VBA in Excel, I get this error message
Syntax Error in Insert into Statement
Kindly confirm shall I use "Logical" as column name or this is the reserved keyword?
Thanks in advance.
There isn't a problem with your field name, you just need to enclose your INSERT column name in square brackets. You also need to choose a valid value in the VALUES clause:
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES (TRUE);
If you want to be prompted for the value to insert, you can use a parameter:
PARAMETERS [Please enter a Boolean value] YesNo;
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES ([Please enter a Boolean value]);
I presume you are trying to do this insert using VBA? If so, your syntax in building the SQL statement is correct, except you have some punctuation missing: double-quotes on each end.
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ")"
Further, as you have split the string over two lines (breaking before VALUES), you must also terminate the first line of the string with: ' " & _' (space,double-quote,space, ampersand, space, underscore) in order to indicate that the string continues to the next line. Then you begin the next line with double-quotes:
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES (" & Logicalnme & ")"
In VBA the code should look like this:
Docmd.RunSQL("INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ");"
The SQL query you alluded to - have you tried to execute it manually in the query editor using the same value(s) you are trying to pass from Excel? That would immediately provide more verbose feedback if there is an issue with the query or the data.
Regarding the Boolean field, make sure you are receiving a True/False that you are expecting, not a bit field, 0 and 1. I like to make quick log entries in a table or a file when troubleshooting to see the raw data.
Use Cbool function:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Cbool(Logicalnme) & ")
Add single quotes around values?
sql = "INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES ('" & Logicalnme & "')"
docmd.runsql sql

How to insert in to MDB using vb.net?

Dim MyInsert As String = "INSERT INTO Inventory(userid,
Type,Number) Values(" & _
txtEquipCat.text & "," & _
Type.Text & "," & _
Number.text & ")"
while executing this im getting
syntax error:Insert in to statement
error.
How to insert keywords like type and number in to MDB?
I want to specify the columnname while insert.
First of all, use parameters. Secondly, your string concoction isn't putting "quotes" around the text.
That is, VALUES ('" & txtEquipCat.Text & "',...
Don't try to fix it like that though.
Use parameters: VALUES (?, ?, ?)
cmd.Parameters.AddWithValue("?", txtEquipCat.Text)
Notice with parameters, you do not have to worry about any quotation marks. The parameters have to be entered in order, so the first "?" corresponds to txtEquipCat, the second to Type.Text, etc.

Search Criteria Form

So I've managed to get my criteria form up and going in access, and it searchs Name/City , but it only searches for the EXACT city name, even though ive given it a wildcard, and the name field works as a search any part of the field? Anyone know why? here is my code:
'Text field example. Use quotes around the value in the string.
If Not IsNull(Me.txtFilterCity) Then
strWhere = strWhere & "([City] Like ""*" & Me.txtFilterCity & "*"") AND "
End If
'Another text field example. Use Like to find anywhere in the field.
If Not IsNull(Me.txtFilterMainName) Then
strWhere = strWhere & "([MainName] Like ""*" & Me.txtFilterMainName & "*"") AND "
End If
Thanks!
Here is a different approach to building strWhere.
' Text field example. Use quotes around the value in the string. '
If Not IsNull(Me.txtFilterCity) Then
strWhere = strWhere & " AND City Like ""*" & Me.txtFilterCity & "*"""
End If
' Another text field example. Use Like to find anywhere in the field. '
If Not IsNull(Me.txtFilterMainName) Then
strWhere = strWhere & " AND MainName Like ""*" & Me.txtFilterMainName & "*"""
End If
' chop off leading AND '
strWhere = Mid(strWhere, 6)
Debug.Print strWhere
I discarded the parentheses and square brackets because they weren't needed here. Square brackets surrounding a field name are needed if the field name includes spaces, punctuation characters, etc. Square brackets are also useful if the field name is a reserved word. I prefer to use only characters which don't require bracketing in object names, and avoid reserved words as object names.
if you are using access then
* allows you to match any string of any length (including zero length)
? allows you to match on a single character
# allows you to match on a single numeric digit
eg:
Like 'b*' would return all values that start with b
Like '*b*' would return all values that contain b
Like '*b' would return all values that end with b
Like 'b?' would return all values that start with b and are 2 characters in length
Like 'b#' would return all values that start with b and are 2 characters in length where the second character is a number

Escaping ' in Access SQL

I'm trying to do a domain lookup in vba with something like this:
DLookup("island", "villages", "village = '" & txtVillage & "'")
This works fine until txtVillage is something like Dillon's Bay, when the apostrophe is taken to be a single quote, and I get a run-time error.
I've written a trivial function that escapes single quotes - it replaces "'" with "''". This seems to be something that comes up fairly often, but I can't find any reference to a built-in function that does the same. Have I missed something?
The "Replace" function should do the trick. Based on your code above:
DLookup("island", "villages", "village = '" & Replace(txtVillage, "'", "''") & "'")
It's worse than you think. Think about what would happen if someone entered a value like this, and you haven't escaped anything:
'); DROP TABLE [YourTable]
Not pretty.
The reason there's no built in function to simply escape an apostrophe is because the correct way to handle this is to use query parameters. For an Ole/Access style query you'd set this as your query string:
DLookup("island", "village", "village = ? ")
And then set the parameter separately. I don't know how you go about setting the parameter value from vba, though.
Though the shorthand domain functions such as DLookup are tempting, they have their disadvantages. The equivalent Jet SQL is something like
SELECT FIRST(island)
FROM villages
WHERE village = ?;
If you have more than one matching candidate it will pick the 'first' one, the definition of 'first' is implementation (SQL engine) dependent and undefined for the Jet/ACE engine IIRC. Do you know which one would be first? If you don’t then steer clear of DLookup :)
[For interest, the answer for Jet/ACE will either be the minimum value based on the clusterd index at the time the database file was last compacted or the first (valid time) inserted value if the database has never been compacted. Clustered index is in turn determined by the PRIAMRY KEY if persent otherwise a UNIQUE constraint or index defined on NOT NULL columns, otherwise the first (valid time) inserted row. What if there is more than one UNIQUE constraint or index defined on NOT NULL columns, which one would be used for clustering? I've no idea! I trust you get the idea that 'first' is not easy to determine, even when you know how!]
I've also seen advice from Microsoft to avoid using domain aggregate functions from an optimization point of view:
Information about query performance in an Access database
http://support.microsoft.com/kb/209126
"Avoid using domain aggregate functions, such as the DLookup function... the Jet database engine cannot optimize queries that use domain aggregate functions"
If you choose to re-write using a query you can then take advantage of the PARAMETERS syntax, or you may prefer the Jet 4.0/ACE PROCEDURE syntax e.g. something like
CREATE PROCEDURE GetUniqueIslandName
(
:village_name VARCHAR(60)
)
AS
SELECT V1.island_name
FROM Villages AS V1
WHERE V1.village_name = :village_name
AND EXISTS
(
SELECT V2.village_name
FROM Villages AS V2
WHERE V2.village_name = V1.village_name
GROUP
BY V2.village_name
HAVING COUNT(*) = 1
);
This way you can use the engine's own functionality -- or at least that of its data providers -- to escape all characters (not merely double- and single quotes) as necessary.
But then, it should be like this (with one more doublequote each):
sSQL = "SELECT * FROM tblTranslation WHERE fldEnglish=""" & myString & """;"
Or what I prefer:
Make a function to escape single quotes, because "escaping" with "[]" would not allow these characters in your string...
Public Function fncSQLStr(varStr As Variant) As String
If IsNull(varStr) Then
fncSQLStr = ""
Else
fncSQLStr = Replace(Trim(varStr), "'", "''")
End If
End Function
I use this function for all my SQL-queries, like SELECT, INSERT and UPDATE (and in the WHERE clause as well...)
strSQL = "INSERT INTO tbl" &
" (fld1, fld2)" & _
" VALUES ('" & fncSQLStr(str1) & "', '" & fncSQLStr(Me.tfFld2.Value) & "');"
or
strSQL = "UPDATE tbl" & _
" SET fld1='" & fncSQLStr(str1) & "', fld2='" & fncSQLStr(Me.tfFld2.Value) & "'" & _
" WHERE fld3='" & fncSQLStr(str3) & "';"
I believe access can use Chr$(34) and happily have single quotes/apostrophes inside.
eg
DLookup("island", "villages", "village = " & chr$(34) & nonEscapedString & chr$(34))
Though then you'd have to escape the chr$(34) (")
You can use the Replace function.
Dim escapedString as String
escapedString = Replace(nonescapedString, "'", "''")
Parametrized queries such as Joel Coehoorn suggested are the way to go, instead of doing concatenation in query string. First - avoids certain security risks, second - I am reasonably certain it takes escaping into engine's own hands and you don't have to worry about that.
By the way, here's my EscapeQuotes function
Public Function EscapeQuotes(s As String) As String
If s = "" Then
EscapeQuotes = ""
ElseIf Left(s, 1) = "'" Then
EscapeQuotes = "''" & EscapeQuotes(Mid(s, 2))
Else
EscapeQuotes = Left(s, 1) & EscapeQuotes(Mid(s, 2))
End If
End Function
For who having trouble with single quotation and Replace function, this line may save your day ^o^
Replace(result, "'", "''", , , vbBinaryCompare)
put brackets around the criteria that might have an apostrophe in it.
SOmething like:
DLookup("island", "villages", "village = '[" & txtVillage & "]'")
They might need to be outside the single quotes or just around txtVillage like:
DLookup("island", "villages", "village = '" & [txtVillage] & "'")
But if you find the right combination, it will take care of the apostrophe.
Keith B
My solution is much simpler. Originally, I used this SQL expression to create an ADO recordset:
Dim sSQL as String
sSQL="SELECT * FROM tblTranslation WHERE fldEnglish='" & myString & "';"
When myString had an apostrophe in it, like Int'l Electrics, my program would halt. Using double quotes solved the problem.
sSQL="SELECT * FROM tblTranslation WHERE fldEnglish="" & myString & "";"