vb .net CDATA for storing SQL multiline string, mixing with VB variables

5.6k views Asked by At

I'm using CDATA to store all multiline SQL string "as is" (thanks some stackoverflow old answer) like this:

Dim cmd As String = <![CDATA[
INSERT INTO devices
VALUES (
    NULL , 
    'ONE', 
    'TWO', 
    (
        SELECT manufacturer_id FROM manufacturers WHERE manufacturer_name = "Bloom"
    )
)
]]>.Value()

The problem is I need to brake this for using VB variables. There is another way instead of multiple CDATA's ?

<![CDATA[ ...... ]]>.Value() + myVBvar +  <![CDATA[ ...... ]]>.Value()
2

There are 2 answers

0
Sam Axe On BEST ANSWER

Try using SqlParameters

Dim commandString As String = <![CDATA[
  INSERT INTO blah VALUES (@One, @Two, @Three, @n)
 ]]>,Value()

Using command As SqlCommand = new SqlCommand(commandString, connection)
  command.Parameters.AddWithValue("@One", valueOne)
  command.Parameters.AddWithValue("@Two", valueTwo) '  etc...

  '  command.execute
End Using
0
Nelson On

I'm re-posting a variant of my answer from "Multiline strings in VB.NET" because it is relevant.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim cmd As String = <sql><![CDATA[
INSERT INTO devices
VALUES (
  NULL , 
  ']]><%= varOne %><![CDATA[', 
  ']]><%= varTwo %><![CDATA[', 
  (
    SELECT manufacturer_id
    FROM manufacturers
    WHERE manufacturer_name = "]]><%= manufacturerName %><![CDATA["
  )
)
]]></sql>.value