Removing first character from a column if it starts with 0 - sql

I have an oracle table, a_abc that have three columns (name, ID and address). The data for this table will be extracted from a txt file. How to remove the first character in ID column if it starts with number '0'. I need a VB solution. This is what Ive done so far now
Private Sub ReadData()
Dim rowvalue As String
Dim cellvalue(20) As String
Dim header As String = "ID"
Dim streamReader As IO.StreamReader = New IO.StreamReader("D:\local_costctr.txt")
'Reading CSV file content
While streamReader.Peek() <> -1
rowvalue = streamReader.ReadLine()
cellvalue = rowvalue.Split("|") 'check what is ur separator
ConnectOracle()
mySQLcmd.Connection = myConn
If SQL.Length > 0 Then
SQL.Replace(SQL.ToString, "")
End If
SQL.Append("insert into a_abc (name ,ID ,address) ")
SQL.Append(" values ('" & cellvalue(0) & "' ,'" & cellvalue(1) & "','" & cellvalue(2) & "') ")
Console.WriteLine(header)
Console.WriteLine(header.Trim({"0"c}))
Try
mySQLcmd.CommandText = SQL.ToString
mySQLcmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error " & ex.Message.ToString)
End Try
End While
End Sub
If there is more than one leading zero, I want all of them removed.

The ltrim function should do the trick:
SELECT name, LTRIM(id, '0'), address
FROM a_abc
EDIT:
Now that the question was edited, I see you refer inserting the data, not querying it. The same solution could be applied on an insert too though:
SQL.Append("insert into a_abc (name ,ID ,address) ")
SQL.Append(" values ('" & cellvalue(0) & "', LTRIM(" & cellvalue(1) & ", '0'), '" & cellvalue(2) & "') ")

While you are extracting the data from the txt-file and you come across the ID-field:
For Each line As String In IO.File.ReadAllLines("yourpath")
If "myID".Substring(0, 1) = "0" Then
'take the "myID" without the leading 0
"myID".Substring(1)
End if
Next
Depending on your case you might need Null-checks etc...
Edited for your code:
Replace cellvalue(1) in the SQL.append by:
IIF(cellvalue(1).Substring(0, 1) = "0",cellvalue(1).Substring(1),cellvalue(1))

Related

Represent field in DB by variable

I have a project which is linked with a MDB file. I need to filter records of a table based on a condition, and both "field name" and the value or conditions should be passed to a Sub via variables. The select statement doesn't work. Did I miss something?
Dim Result() As DataRow
Dim strField As String = "asset_code"
Dim dblValue As Double = 3
Dim tblName as Datatable = AssetsDataSet.Assets
Result = tblName.Select(" '" & strField & "' = '" & dblValue& "' ")
I suspect that you need to loose the single quotes around the field name and as the data because it looks like it is numeric:
Result = tblName.Select(strField & " = " & cstr(dblValue) )
With string data you need to use a function:
Result = tblName.Select("textfield = " & cSQL(StringData) )
Function cSQL(psTextData As String) As String
' Replace any single quotes to be 2 single quotes
Return "'" + Replace(psTextData, "'", "''") + "'"
End Function

How to get rid of the first concatenation symbol

I'm looping a table database to catch the first name of some rows
The code is like:
Try
While (readerFirstName.Read())
SearchedName = readerFirstName("parteA")
CombinatedNames = CombinatedNames & " & " & SearchedName
End While
Catch ex As Exception
MsgBox(ex.ToString())
End Try
And the desired result si something like
Mike & Eric & Tom
but I get
& Mike & Eric & Tom
I think I can get rid of the first " &" after the string formation using String.TrimStart
but there's a better way to cut the first "& "?
Try replacing your loop:
While (readerFirstName.Read())
SearchedName = readerFirstName("parteA")
CombinatedNames = CombinatedNames & " & " & SearchedName
End While
With this one:
Dim names As New List(Of String)()
While (readerFirstName.Read())
names.Add(readerFirstName("parteA"))
End While
CombinatedNames = String.Join(" & ", names)
The main idea here is to use the String.Join method to concatenate the single names in one single operation. That method acts on collections, so you will first have to read the single items into a collection names.
This method will take care to add the separator string " & " between items, never before the first or after the last, so you will not end up with a leading or trailing separator (unless you have an empty item in your list).
P.S.: If you happen to know beforehand how many names will be read from readerFirstNames, you could optimise memory usage of my suggested code by passing the name count to the List(Of T) constructor (as the capacity parameter).
You can check the contains in combine string before adding text in it
While (readerFirstName.Read())
SearchedName = readerFirstName("parteA")
If Not isNullOrEmpty(CombinatedNames) Then
CombinatedNames = CombinatedNames & " & " & SearchedName
Else
CombinatedNames = SearchedName
End If
End While
The other answers are the usual way to do it, but here are few lazier alternatives:
this will remove the first 3 characters:
CombinatedNames = Mid( CombinatedNames , 4 )
this will trim and & from the beginning of the string:
CombinatedNames = CombinatedNames.TrimStart(" "c, "&"c)
or you can just read the first record and then concatenate the rest:
CombinatedNames = If(readerFirstName.Read, readerFirstName!parteA.ToString, "")
While readerFirstName.Read
CombinatedNames &= " & " & readerFirstName!parteA.ToString
End While

Access VBA SQL Run-time error 3134 INSERT INTO

I have a VBA code for an Access 2013, and i want to run INSERT INTO, but when i try to run it, it keeps drop the messeage "Run-time error 3134 Syntax error in 'INSERT INTO'".
There is my code:
Private Sub Parancsgomb35_Click()
Set valamiami = Me.Szöveg29
Dim neveteke As String
Me.KombináltLista27.SetFocus
neveteke = Me.KombináltLista27.Value
Set db_number = Me.Szöveg15
Dim sql_cucc As String
Set rs = CurrentDb.OpenRecordset("SELECT sarzsszám, cikkszam, me, afa, behozatali, netto FROM torzslapok WHERE neve='" & neveteke & "'")
While Not rs.EOF
Set afaka = rs.Fields("afa")
Set sarzsszamka = rs.Fields("sarzsszám")
Set mennka = rs.Fields("me")
Set cikkszamka = rs.Fields("cikkszam")
Set behozatalika = rs.Fields("behozatali")
Set nettoka = rs.Fields("netto")
sql_cucc = "INSERT INTO BE-ALPHAVET(neve, afa, behozatali, netto, db, sarzsszám, cikkszam, me) VALUES('" & neveteke & "','" & afaka & "','" & behozatalika & "','" & nettoka & "','" & db_number & "','" & sarzsszamka & "','" & cikkszamka & "','" & mennka & "');"
CurrentDb.Execute sql_cucc
Wend
End Sub
valamiami = DATE like yyyy.mm.dd
neveteke = STRING
KombináltLista27 = STRING (COMBINE LIST with ine select only)
db_number = INTERGER
sql_cucc = STRING
afaka = INTEGER
sarzsszamka = STRING
mennka = STRING
cikkszamka = STRING
behozatalika = INTEGER
nettoka = INTEGER
I read a lot of forum, but a didn't find any answer..
Can somebody explain for me what is the problem?
Thanks and love!
Your INSERT starts as:
INSERT INTO BE-ALPHAVET(neve, afa, behozatali, netto, db,
sarzsszám, cikkszam, me)
The - is interpreted as a minus sign. You need to escape the table name:
INSERT INTO [BE-ALPHAVET](neve, afa, behozatali, netto, db,
sarzsszám, cikkszam, me)
Or, better yet, change it to an underscore (_) so you don't have to escape the name at all.

SQL/VB.NET Search-Function looking for at least one correct input

I'm writing a program in Visual Basic about Databases. Now I have a Sub/Function who searches the database for correct inputs. I have five text boxes where the user can put in something for each data field.
If txtBox1.Text <> "" Or txtBox2.Text <> "" Or txtBox3.Text <> "" Or txtBox4.Text <> "" Or txtBox5.Text <> "" Then
Try
connection.Open()
command.CommandText = "SELECT * from lager WHERE (lager_waren_id LIKE '" & txtBox1.Text & "' OR lager_warenanzahl LIKE '" & txtBox2.Text & "' OR lager_warenname LIKE '%" & txtBox3.Text & "%' OR lager_warengewicht LIKE '" & txtBox4.Text & "%' OR lager_waren_verkaufspreis LIKE '" & txtBox5.Text & "%');"
reader = command.ExecuteReader()
FormKunde.Enabled = True
FormKunde.lstViewKundeStore.Items.Clear()
Do While reader.Read()
Dim lstViewItem As New ListViewItem(reader("lager_waren_id").ToString())
lstViewItem.SubItems.Add(reader("lager_warenanzahl").ToString())
lstViewItem.SubItems.Add(reader("lager_warenname").ToString())
lstViewItem.SubItems.Add(reader("lager_warengewicht").ToString())
lstViewItem.SubItems.Add(reader("lager_waren_verkaufspreis").ToString())
FormKunde.lstViewKundeStore.Items.Add(lstViewItem)
Loop
reader.Close()
FormKunde.Enabled = False
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
connection.Close()
Else
MessageBox.Show("Please fill in something in the text fields")
Exit Sub
End If
I'm aksing the database if at least one text field has some input that matches to the data field it belongs to. But when I put something in, doesn't matter how much, nothing happens in my list view. It just loads all data back in the list view. When I try to do "AND" instead of "OR", it works only if i fill all text fields with the correct datas for one data set. But I want, that it finds all data sets.
An example:
I have two data sets where the names are "App" and "Apple". When i just fill in "Ap" in the field for names (nothing in the others) it shows me both. I think it should work with "OR", but it just does nothing.
I'm really confused how to solve this, I hope anyone has a guess. Thank you!
Your problem is that your query always uses all the conditions also when there is no input in the relevant textboxes. In this way your LIKEs become LIKE '%%' and, of course, this matches every record.
You need to add the conditions only if the textboxes are not empty or null.
So you need to build your query in parts after checking if the textbox contains any value to search for.
connection.Open()
Dim sql = "SELECT * from lager WHERE "
if Not string.IsNullOrWhiteSpace(textBox1.Text) Then
sql = sql & "lager_waren_id LIKE #p1 OR "
command.Parameters.AddWithValue("#p1", textBox1.Text)
End If
if Not string.IsNullOrWhiteSpace(textBox2.Text) Then
sql = sql & "lager_warenanzahl LIKE #p2 OR "
command.Parameters.AddWithValue("#p2", textBox2.Text)
End If
if Not string.IsNullOrWhiteSpace(textBox3.Text) Then
sql = sql & "lager_warenname LIKE #p3 OR "
command.Parameters.AddWithValue("#p3", "%" & textBox3.Text & "%")
End If
if Not string.IsNullOrWhiteSpace(textBox4.Text) Then
sql = sql & "lager_warengewicht LIKE #p4 OR "
command.Parameters.AddWithValue("#p4", textBox4.Text & "%")
End If
if Not string.IsNullOrWhiteSpace(textBox5.Text) Then
sql = sql & "lager_waren_verkaufspreis LIKE #p5 OR "
command.Parameters.AddWithValue("#p5", textBox5.Text & "%")
End If
' Remove the last OR if any ....'
if sql.EndsWith(" OR ") then
sql = sql.Substring(0, sql.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
if sql.EndsWith(" WHERE ") then
sql = sql.Substring(0, sql.Length - 7)
End If
command.CommandText = sql
reader = command.ExecuteReader()
Notice also that you should ALWAYS use a parameterized query to avoid Sql Injection particularly when you get your inputs directly from your user. (Not to mention the problems with typed texts that contain a single quote)
I hope I understand your problem correctly. I am sure there are better ways to do this and my VB is rusty but something like this may work
Dim query As String = "SELECT * FROM lager"
Function addField (ByVal query As String, ByVal value as String, ByVal field as String) As String
addField = query
If value <> "" Then
If query.IndexOf("where", 0, StringComparison.CurrentCultureIgnoreCase) > -1 Then
addField = query & " AND " & field & " LIKE '%" & value & "%'"
Else
addField = query & " WHERE " & field & " LIKE '%" & value & "%'"
End If
End If
End Function
query = addField(query, txtBox1.Text, "lager_waren_id")
query = addField(query, txtBox2.Text, "lager_warenanzahl")
'...continue adding fields...'
command.CommandText = query
This should make it so your query string only includes the populated fields

vb.net SQL date to time conversion issue

The error is: Conversion failed when converting date and/or time from character string.
Basically I'm trying to make it so that when someone clicks a location in a list box it increments the correct field in a Stats table by 1 to say that they clicked the location. I've been trying to solve this for a while now and can't get anywhere. My date is in date format, and so is the Date field in my Stats table. My code can be seen below.
Dim Current As String
Dim Check As String
Dim objCmd2 As Object
Dim iCount As Integer
Dim tDate As Date
Current = LocBox.SelectedItem
Check = LocList.FindString(Current)
If Check > -1 Then
MsgBox("You have already selected this place to visit")
Else
LocList.Items.Add(Current)
ObjDataReader.Close()
tDate = Date.Today
MessageBox.Show(tDate)
tDate = tDate.ToString()
objCmd2 = New SqlCommand("SELECT " & Replace(Current, " ", "_") & " FROM Stats WHERE Date = '" & tDate & "'", objConn)
ObjDataReader = objCmd2.ExecuteReader
If ObjDataReader.HasRows Then
ObjDataReader.Read()
If ObjDataReader(0) Is DBNull.Value Then
iCount = 0
Else
iCount = ObjDataReader(0)
End If
Else
iCount = 0
End If
objCmd = New SqlCommand("INSERT INTO Stats(Date," & Replace(Current, " ", "_") & ") Values('" & tDate.Date & "'," & iCount & " )", objConn)
ObjDataReader.Close()
objCmd.ExecuteNonQuery()
objConn.Close()
Thanks in advance.
The issue comes in with the second SQL statement I think. I don't understand why adding a date into a date field would be an issue, I've tried adding it as a string which didn't work. Thanks for all the answers so far.
As Martin points out this is probably the best choice:
int colnum = ConvertColumnNameToNumber(Current)
objCmd2 = New SqlCommand("SELECT "+colnum.ToString()+" FROM Stats WHERE [Date] = #inDate", objConn)
objCmd2.Parameters.Add("#inDate",SqlDbType.DateTime).value = tDate
Not tested or compiled might have typos.
Note the use of colnum above. Because you can't use parameters for column names you have to use the column number. If you have code that returns an integer as a return value you can protect against injection (it can only a number).
I'm going to guess the issue is here: MessageBox.Show(tDate)
You need to convert the date to a string using tDate.ToString or whatever other method you want.
Are you getting compile errors? I always code with Option Strict On, and your code would definitely bring up errors where you are not converting variables.
I may be off base but you have tDate as a Date variable type and then your trying to send it a string, you can just use tDate.ToString() in your SqlCommand lines and not convert it first.
Try Removing the apostrophes from around tdate so that it is...
objCmd2 = New SqlCommand("SELECT " & Replace(Current, " ", "_") & " FROM Stats WHERE Date = " & tDate, objConn)
and
objCmd = New SqlCommand("INSERT INTO Stats(Date," & Replace(Current, " ", "_") & ") Values(" & tDate.Date & "," & iCount & " )", objConn)