String conversion for SQL select statement - sql

Using a SELECT statement I query a database and get back a result in the format: name1,name2,name3
Depending on the database entry this result could have any number of names: name1,name2...name(n)
I would like to use this data to query another database like so:
SELECT Name, SerialNo, Model FROM InstrumentTable where ID=1 and InstName IN name1,name2,name3
In order to do this I need to convert name1,name2,name3 to ('name1','name2','name3')
I have tried splitting the String into an array of Strings
Dim ref1s As String = cmdf1.ExecuteScalar()
Dim fields() As String = Nothing
fields = ref1s.Split(",")
and then concatenating them in an array
For i As Integer = 0 To fields.Count - 1
MsgBox(String.Concat("'", fields(i), "'"))
Next
but I haven't been able to figure out how to do it yet.
Adding the brackets at the start and end of the string shouldn't be a problem just adding the quotes to each name and separating them with a comma is the issue.
Can anyone help me with this?

You got a bit previous
For i As Integer = 0 To fields.Count - 1
fields[i] = String.Concat("'",fields[i],"'")
Next
Then
strValue = fields.Join(',')

user557425,
Something like this might point you in the right direction:
Dim lst As List(Of String)
For i As Integer = 0 to fields.Count - 1
if i = fields.Count - 1 Then
lst.Add(fields(i) & "'")
Else
lst.Add(fields(i) & "','")
End if
Next
Dim sqlSB As StringBuilder
sqlSB.Append("SELECT * FROM TABLE WHERE BLAH IN(")
For each s As String in lst
sqlSB.Append(s)
Next
'use the stringbuilder as command text in a SqlCommand...

Related

What is the simplest way to get the second item of each row in a string file

I have a String file with 8 items (separated by commas) in each row, e.g., CA,23456,aName,aType,anotherName,aWord,secondword,number. I want to create a new string of items consisting of the 2nd item (an Integer) of each row of the original file. I know there are many ways to do this but someone out there knows how to do it with very few lines of code, which is what I am looking for. I prefer not to use a parser.
The way to show what I have tried is to look at the code below.
Dim sn2 As String = ""
Dim sn2S As String = ""
Using readFile As New StreamReader(newFile1)
Do While readFile.Peek() <> -1
sn2S = readFile.ReadLine(1)
sn2 = sn2 & sn2S & ","
Loop
End Using
The code returns the second character of each row not the second item. What I hope to get is a string that looks like: 123,1345,4325,3321,3456,3211 etc. Where each number is the second item in each row of the original file.
You could split it up by cells
Dim row As String = "CA,23456,aName,aType,anotherName,aWord,secondword,number"
Dim cells() As String = row.Split(",")
Dim cellValue As String = cells(1)
But in your case, I would just do a search and Substring by the index of the delimiter.
Dim startPosition As Integer = row.IndexOf(",") + 1
Dim endPosition As Integer = row.IndexOf(",", startPosition)
Dim cellValue As String = row.Substring(startPosition, endPosition - startPosition)
If you have the whole file in memory, there could be some regex that could do the job with one pass.
As for this line
sn2 = sn2 & sn2S & ","
You might want to check at doing a join or using stringbuilder.
You could try
Dim sn2 As String = ""
Dim sn2S(7) As String = ""
Using readFile As New StreamReader(newFile1)
Do While readFile.Peek() <> -1
Array.Clear(sn25,0,sn25.Length)
sn2S = readFile.ReadLine(1).Split(",")
sn2 = sn2 & sn2S(1) & ","
Loop
End Using
In one line
Dim sn2 = String.Join(",", File.ReadAllLines(newFile1).Select(Function(s) s.Split(","c)(1)))
From the inside-out:
File.ReadAllLines(newFile1) splits the file into lines and results in a string array holding those lines, which is fed into...
...Select(Function(s) s.Split(","c)(1)) which operates on each line by splitting the line by comma s.Split(","c) and then indexing the resulting array (1) to return the second (zero-based) element. This is fed into...
String.Join(",", ... ) which takes those second elements and joins then together with comma.

How to increase numeric value present in a string

I'm using this query in vb.net
Raw_data = Alltext_line.Substring(Alltext_line.IndexOf("R|1"))
and I want to increase R|1 to R|2, R|3 and so on using for loop.
I tried it many ways but getting error
string to double is invalid
any help will be appreciated
You must first extract the number from the string. If the text part ("R") is always separated from the number part by a "|", you can easily separated the two with Split:
Dim Alltext_line = "R|1"
Dim parts = Alltext_line.Split("|"c)
parts is a string array. If this results in two parts, the string has the expected shape and we can try to convert the second part to a number, increase it and then re-create the string using the increased number
Dim n As Integer
If parts.Length = 2 AndAlso Integer.TryParse(parts(1), n) Then
Alltext_line = parts(0) & "|" & (n + 1)
End If
Note that the c in "|"c denotes a Char constant in VB.
An alternate solution that takes advantage of the String type defined as an Array of Chars.
I'm using string.Concat() to patch together the resulting IEnumerable(Of Char) and CInt() to convert the string to an Integer and sum 1 to its value.
Raw_data = "R|151"
Dim Result As String = Raw_data.Substring(0, 2) & (CInt(String.Concat(Raw_data.Skip(2))) + 1).ToString
This, of course, supposes that the source string is directly convertible to an Integer type.
If a value check is instead required, you can use Integer.TryParse() to perform the validation:
Dim ValuePart As String = Raw_data.Substring(2)
Dim Value As Integer = 0
If Integer.TryParse(ValuePart, Value) Then
Raw_data = Raw_data.Substring(0, 2) & (Value + 1).ToString
End If
If the left part can be variable (in size or content), the answer provided by Olivier Jacot-Descombes is covering this scenario already.
Sub IncrVal()
Dim s = "R|1"
For x% = 1 To 10
s = Regex.Replace(s, "[0-9]+", Function(m) Integer.Parse(m.Value) + 1)
Next
End Sub

Insert number of record based on checkboxlist selected value in vb.net

I have this skill checkboxlist which contains skills that can be selected by the user. If the user select two skills,two records will be inserted to the table.
I tried this one:
Dim varSkillID As Integer()
varSkillID = split(skills, ",")
If varSkillID(0).value > 0 Then
Dim sql As String = Nothing
For I = 0 To varSkillID()
sql = "INSERT INTO tblConstituentSkills (skillID) VALUES ( " & varSkillID.Value & ")"
Next I
end if
but its not working. Thanks!
I also tried this code.
Dim varSkillID() As String = Split(skillID, ",")
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then
Using sql As New SqlProcedure("spInsertSkill")
sql.AddParameter("#ConstituentIdNo", constituentIdNo)
sql.AddParameter("#skillID", varSkillID(i))
sql.ExecuteNonQuery()
End Using
End If
Next i
It works when I only select single skill. But if I select two or more skills this error appears "Nullable object must have a value."
please use the editor help to design your request. It is very hard to read.
What does the errormessage say?
There is an End If missing
Where does constituentIdNo.Value is coming from?
To call the Sub:
Call r101("123456", "1,2,3,4")
the Sub:
Public Sub r101(ByVal constituentIdNo As String, ByVal skills As String)
Dim varSkillID() As String = Split(skills, ",")
Dim sql As String = Nothing
For i As Integer = 0 To varSkillID.Length - 1
If varSkillID(i) <> "" Then sql = "INSERT INTO tblConstituentSkills (ConstituentIdNo, skillID) VALUES (" & constituentIdNo & ", " & varSkillID(i) & ")"
Next i
End Sub
This is not the cleanest code, but the best I could create from your given feedback.
I don't see why to convert skills to integer.
I just read this and saved me.separate comma separated values and store in table in sql server
Thanks stackoverflow!you're a savior!

converting dataset.Compute("Sum(TARGET_AREA)", "") to .toString("N")

I am trying to convert my computed database columns in my datagrid. I was able to compute the columns and wanted to fix the format of the results.
Label18.Text = dataset.Compute("Sum(TARGET_AREA)", "") & " (ha)"
An example of my output is 100000.00 (ha)
What I wanted for my output is to look like this 100,000.00 (ha)
I tried using .toString("N") but no luck.
my column type is Decimal and the others were Double.
Any idea on how to fix it?
You could use String.Format method.
Example
value = 1234.567890
Console.WriteLine(value.ToString("0,0.00", CultureInfo.InvariantCulture))
Source: MSDN Custom Numeric Format Strings.
Here is an example using a DataTable - Note that you may want to check the sum if the column allows nulls. Also, the sum here is invoked over the datatable object not the dataset (as in your question) - This code has been automatically translated from C# - I assume it syntactically OK.
Dim dataset As New DataSet("ds1")
Dim dt As New DataTable("dt")
Dim dc As DataColumn = dt.Columns.Add("TARGET_AREA", GetType(System.Decimal))
Dim dr As DataRow = dt.Rows.Add()
dr("TARGET_AREA") = 100000.0
Dim finalResult As String = ""
Dim value As Decimal
If dt.Rows.Count > 0 Then
Dim result_obj As Object = dt.Compute("Sum(TARGET_AREA)", "")
If result_obj Is System.DBNull.Value Then
value = 0
Else
value = Convert.ToDecimal(result_obj)
End If
finalResult = String.Format(value.ToString("0,0.00", System.Globalization.CultureInfo.InvariantCulture)) & " (ha)"
Console.WriteLine(finalResult)
End If
Console.Read()
Return

Extract characters from a long string and reformat the output to CSV by using keywords with VB.net

I am new to VB.Net 2008. I have a task to resolve, it is regading extracting characters from a long string to the console, the extracted text shall be reformatted and saved into a CSV file. The string comes out of a database.
It looks something like: UNH+RAM6957+ORDERS:D:96A:UN:EGC103'BGM+38G::ZEW+REQEST6957+9'DTM+Z05:0:805'DTM+137:20100930154
The values are seperated by '.
I can query the database and display the string on the console, but now I need to extract the
Keyword 'ORDERS' for example, and lets say it's following 5 Characters. So the output should look like: ORDERS:D:96A then I need to extract the keyword 'BGM' and its following five characters so the output should look like: BGM+38G:
After extracting all the keywords, the result should be comma seperated and look like:
ORDERS:D:96A,BGM+38G: it should be saved into a CSV file automatically.
I tried already:
'Lookup for containing KeyWords
Dim FoundPosition1 = p_EDI.Contains("ORDERS")
Console.WriteLine(FoundPosition1)
Which gives the starting position of the Keyword.
I tried to trim the whole thing around the keyword "DTM". The EDI variable holds the entire string from the Database:
Dim FoundPosition2 = EDI
FoundPosition2 = Trim(Mid(EDI, InStr(EDI, "DTM")))
Console.WriteLine(FoundPosition2)
Can someone help please?
Thank you in advance!
To illustrate the steps involved:
' Find the position where ORDERS is in the string.'
Dim foundPosition = EDI.IndexOf("ORDERS")
' Start at that position and extract ORDERS + 5 characters = 11 characters in total.'
Dim ordersData = EDI.SubString(foundPosition, 11)
' Find the position where BGM is in the string.'
Dim foundPosition2 = EDI.IndexOf("BGM")
' Start at that position and extract BGM + 5 characters = 8 characters in total.'
Dim bgmData = EDI.SubString(foundPosition2, 8)
' Construct the CVS data.'
Dim cvsData = ordersData & "," & bgmData
I don't have my IDE here, but something like this will work:
dim EDI as string = "UNH+RAM6957+ORDERS:D:96A:UN:EGC103'BGM+38G::ZEW+REQEST6957+9'DTM+Z05:0:805'DTM+137:20100930154"
dim result as string = KeywordPlus(EDI, "ORDER", 5) + "," _
+ KeywordPlus(EDI, "BGM", 5)
function KeywordPlus(s as string, keyword as string, length as integer) as string
dim index as integer = s.IndexOf(keyword)
if index = -1 then return ""
return s.substring(index, keyword.length + length)
end function
for the interrested people among us, I have put the code together, and created
a CSV file out of it. Maybe it can be helpful to others...
If EDI.Contains("LOC") Then
Dim foundPosition1 = EDI.IndexOf("LOC")
' Start at that position and extract ORDERS + 5 characters = 11 characters in total.'
Dim locData = EDI.Substring(foundPosition1, 11)
'Console.WriteLine(locData)
Dim FoundPosition2 = EDI.IndexOf("QTY")
Dim qtyData = EDI.Substring(FoundPosition2, 11)
'Console.WriteLine(qtyData)
' Construct the CSV data.
Dim csvData = locData & "," & qtyData
'Console.WriteLine(csvData)
' Creating the CSV File.
Dim csvFile As String = My.Application.Info.DirectoryPath & "\Test.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
outFile.WriteLine(csvData)
outFile.Close()
Console.WriteLine(My.Computer.FileSystem.ReadAllText(csvFile))
End IF
Have fun!