0

Using VB6 and SQL Server

How to insert a string value in the table

Dim a as string
a = 0008", "0009", "1011", "1208

I want to insert this string values in the table

Expected Output

Table1

ID

0008
0009
1011
1208

How to make a query for the above condition.

Need Query Help.

Gopal
  • 11,712
  • 52
  • 154
  • 229

3 Answers3

1

Please try with the below way:

Dim a as string
a = "0008,0009,1011,1208"
dim strArray as string() = Split(a, ",")

b for each item as string in strArray

   query = "INSERT INTO  Table1(ID) values('"&item&"')"
   // Write Connection and Command code here
next

Update:

You can generate insert SQL statement for each item at a time and then write Connection and Command code, that would be more efficient.

dim query as string
for each item as string in strArray
   query = query + "INSERT INTO  Table1(ID) values('"&item&"'); "
next
// Write Connection and Command code here after generating insert statement 
// so that all data will save into database in one shot.
Elias Hossain
  • 4,410
  • 1
  • 19
  • 33
0
DECLARE @Str VARCHAR(100)
SET @Str = '0008", "0009", "1011", "1208'
SET @Str = REPLACE(@Str,'"','')
SELECT * FROM [dbo].Split(@Str) 

You can use Split function from this link.
Check this Split function.
http://blogs.lessthandot.com/index.php/DataMgmt/DBProgramming/split-string-in-sql-server-2005-clr-vs-t

S.K
  • 165
  • 1
  • 13
0

at first u must split this string to a string[]

dim a as string 

a = 0008", "0009", "1011", "1208
dim str as string() = (a.Replace('"',' ')).Split(",")

and if

a = "0008,0009,1011,1208"
dim str as string() = a.Split(",")

now add values in the table with a query on the foreach loop

imaging your table name is testTable andyour column name is ID

 dim query as string
 for each item as string in str

            query = "INSERT INTO  testTable(ID) values('"&item&"')"
 next
Esi
  • 389
  • 5
  • 14
  • `string[] str = a.Split(",");` is supposed to be `dim str as string() = a.Split(",");` – Seph Dec 04 '11 at 06:55
  • yap(;-) but without ';') at first i create sample in the c# and then i forget Correct this sample thanks – Esi Dec 04 '11 at 07:16
  • 2
    And when you're inserting, you should use **parametrized queries** instead of concatenating together your SQL commands! Doing so open the door to SQL injection attacks - not something you want to have to deal with...... – marc_s Dec 04 '11 at 11:21