Question

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()
Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top