views:

1778

answers:

2

I want to add a text box on a web page in order for users to add space delimited tags. When the user submits the page how do I take the tags out of the text box and add each as a record in a SQL database?

I want to use VB.NET.

+2  A: 

Sounds like you want something like:

Using connection as New SqlConnection("connection string")
    connection.Open()

    For Each tag As String In TextBox.Split(CChar(" "))
        Using command as New SqlCommand("INSERT INTO UsedTags(Tag) VALUES(@Tag)", connection)
            command.Parameters.Add("@Tag", SqlDbType.varchar).value = tag

            Try
                command.ExecuteNonQuery()
            Catch ex As SqlException
                Debug.WriteLine(ex.ToString())
            End Try
        End Using
    End For
End Using

Not tested, but should be close enough to your needs.

Sören Kuklau
+1  A: 

My way would be to send the value from the Text Box to a SQL Stored Procedure, have that SPLIT the text, and then insert the individual rows.

All this will be set-based, so very fast.

if you split it in VB.NET and send individual INSERT statements to SQL that will be much slower.

You could convert the Text Box delimited data into XML and send that to SQL, and use that as a basis for your INSERT statements. But personally I think Splitting it in SQL is preferable.

I'll find a link for you

I didn't find a worked example easily, so here's a suggestion

INSERT INTO UsedTags
(
    Tag
)
SELECT SplitValue
FROM dbo.MySplitFunction(@ListOfTags)

See http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648 for recommended SPLIT functions

If you want to just make an INSERT direct from VB.NET you could do something like:

INSERT INTO UsedTags
(
    Tag
)
SELECT "Tag1"
UNION ALL
SELECT "Tag2"

i.e. you generate the compound SELECT statement in VB.NET having split the delimited tag string.

(If there might be duplicate tags, and you want to remove duplicates, use "UNION" instead of "UNION ALL")

Kristen
Given that 1) MSSQL (I assume that's what we're talking about here) has no built-in string splitting function, 2) there is no input set to speak of, 3) there's probably a very small amount of tags, I doubt your performance assumptions.
Sören Kuklau
I don't know VB.NET, but if "command.Parameters.Add" will make round trips to the server for each row then I'm happy to bet you a beer on that one!I agree for small numbers of TAGs the splitting is trivial however done (but for large numbers care is **definitely** needed choosing the SQL method)
Kristen