2

I have a project where we use the SQL queries directly in the code.

Dim strSQL As String = "SELECT P.NAME, C.ID, C.NAME" +
         "FROM PERSONS P " + 
"INNER JOIN CITIES " +
"ON P.IDCITY = C.ID" +
"WHERE P.ID = {0}"

Is a little bit ennoying to format such a query using "" and "+" Is there a way to write the script "As Is" (from a SQL file), without reformating it?

I'd use

strSQL = My.Resources.SELECT_PERSON_WITH_CITY

but in debug I can't see/modify the original query.

I know, I know, this is not a best practice using SQL directly, but however, I use what I have.

PS.

As Conor Gallagher mentioned, in C# there is a way to achieve this:

string x = @"
  my 
  name 
  is {0}";
string y = string.Format(x, "jimmy");

Does anyone know a VB.NET equivalent?

moldovanu
  • 660
  • 3
  • 8
  • 20
  • 1
    Write in C# then you don't have this 'problem' ;). Can't you use Stored Procedures instead? – Ralf de Kleine Apr 17 '12 at 08:52
  • @rdkleine a little bit hard to compose for each select a stored procedure... – moldovanu Apr 17 '12 at 08:57
  • Harder then creating a piece of code? Sp's are easily testable compared to code (build, start app, trial and error). You could also give Entity Framework a try. – Ralf de Kleine Apr 17 '12 at 09:05
  • a large old project is a large old project... – moldovanu Apr 17 '12 at 09:06
  • Actually, question. Why can't you see the original query if you use a resource? In your above sample if you put a watch on strSQL wouldn't it give you the query? – Conor Gallagher Apr 17 '12 at 09:30
  • Conor, I can see it, but afraid can't modify in debug... – moldovanu Apr 17 '12 at 09:47
  • Ok, not being able to modify it sounds more like a VS issue, not a resource issue. Can't fully recall where the setting is but it might be the "Tools -> Options -> Debugging -> Edit and Continue". Once you get the settings right you should have no problems editing the strings. – Conor Gallagher Apr 17 '12 at 09:56

6 Answers6

5

I believe the answer in vb.net is actually No, you can't create strings in vb.net over multiple lines without using " and + etc. In C# you can span strings over multiple lines using the "@" escape character. Bit like this:

string x = @"
  my 
  name 
  is {0}";
string y = string.Format(x, "jimmy");

But VB.Net doesn't have an equivalent.

Update

As per D..'s comment below, Xml Literals could solve this problem. See http://www.codeproject.com/Articles/292152/Mutliline-String-Literals-in-VB-NET

Basically, as per the link, you can do clever stuff like this using Xml Literals:

Dim sourceText As String =
    <string>
        Imports Microsoft.VisualBasic
        Imports System
        Imports System.Collections
        Imports Microsoft.Win32
        Imports System.Linq
        Imports System.Text
        Imports Roslyn.Compilers
        Imports System.ComponentModel
        Imports System.Runtime.CompilerServices
        Imports Roslyn.Compilers.VisualBasic

        Namespace HelloWorld
          Module Program
            Sub Main(args As String())
              Console.WriteLine("Hello, World!")
            End Sub
          End Module
        End Namespace
    </string>

Update 2

Been playing around with this a bit. XmlLiterals are actually really nice! If you wanted to add variables into the loop you can do stuff like this:

Dim x As String
Dim y As String
y = "Jimmy"

x = <string>
        Select *
        From Person
        Where Person.FirstName = <%= y %>
    </string>
Community
  • 1
  • 1
Conor Gallagher
  • 1,500
  • 2
  • 19
  • 42
  • Does VB.NET really have not an equivalent? – moldovanu Apr 17 '12 at 09:07
  • Afraid not. When dealing with special characters the 2 languages are fundamentally quite different. C# uses escape characters such as "@" and "\" to handle special characters, whereas VB.net uses a "ControlChars" class to handle these "special" characters. Another example difference is in C# you can insert a new line using "new line here: \n" but in VB.Net you have to use "new line here: " + ControlChars.NewLine. I've never come across a way around this unfortunately – Conor Gallagher Apr 17 '12 at 09:20
  • @ actually means that its a literal string. The reason that \n works for a new line when you don't use the @ to indicate its a literal is because c# automatically converts it to the new line. If you did @"Whatever \n" you would get output that included the \n. In vb.net all strings are literal and you must escape special characters. – Jay Apr 17 '12 at 09:42
  • Exactly. The whole purpose of @ being to ignore any escape characters in the string (including spanning your strings across muliple lines). – Conor Gallagher Apr 17 '12 at 09:49
  • 2
    Indeed, I was only shooting for further clarification of your comment. You may consider an XML literal something like they show here to get around it: http://www.codeproject.com/Articles/292152/Mutliline-String-Literals-in-VB-NET – Jay Apr 17 '12 at 09:57
  • 1
    No worries, clarification is good! That link to XML Literals is a fantastic shout. Looks like that could work for you @moldovanu ? – Conor Gallagher Apr 17 '12 at 10:05
  • As I have `Option Explicit On` I need to do CStr(...) but really, is a cool idea! – moldovanu Apr 17 '12 at 13:35
  • The small negative point is that I cant declare constants with – moldovanu Apr 18 '12 at 10:51
2

You must use SQLParameters, not format your query manually!!

Dim con AS New SqlConnection("...")
Dim cmd As New SqlCommand(
    "SELECT P.NAME, C.ID, C.NAME FROM PERSONS P " +
    "INNER JOIN CITIES ON P.IDCITY = C.ID " +   
    "WHERE P.ID = @id", con)
cmd.Parameters.AddWithValue("@id" , your_id)
Marco
  • 56,740
  • 14
  • 129
  • 152
  • Thank you, Marco, but my question where related on "how to format the query" – moldovanu Apr 17 '12 at 08:55
  • @moldovanu: I didn't understand your problem, sorry! Anyway, don't "write" your params manually in query, this is my advise :) – Marco Apr 17 '12 at 08:59
  • As I wrote, I understand that this is not the best practice, but however I need an advice. thank you. – moldovanu Apr 17 '12 at 09:05
  • @Marco: If you don't understand the problem, why did you pretend you did by submitting an Answer to the question? – Ross Presser Jun 22 '16 at 16:53
1

I use brijpad to copy Long SQL query, paste in left side, Advance tab > click on text to VB.NET,It will generate equivalent VB.NET string and use it in our code.

If there is any parameter, I use 'custom format' to generate command parameters syntax.

mycmd.Parameters.AddWithValue("@Par" , parVal)
Brij
  • 6,086
  • 9
  • 41
  • 69
  • a little bit strage, it uses ";" in VB.NET and `builder.append("FROM PERSONS P"); builder.append("INNER JOIN CITIES");` What will be that? - "PERSONS PINNER JOIN"? – moldovanu Apr 17 '12 at 09:04
  • It seems bugs...you can try Advance > custom format and enter `builder.append("{0}")` and click OK. Make sure input shouldn't have {0} – Brij Apr 17 '12 at 09:44
1

http://www.dpriver.com/pp/sqlformat.htm

The best side code formatter for me. You just paste the long SQL Statement and it will generate ready-to-copy codes for vbnet. It does not only support VBNet but also C#, PHP, Delphi, and etc.

John Woo
  • 258,903
  • 69
  • 498
  • 492
1

You should really use a parameterised query not raw SQL in your code but to give a possible answer to your question:

You could use a StringBilder class to add improved formatting:

    Dim sb As New StringBuilder()
    With sb
        .Append("SELECT P.NAME, C.ID, C.NAME")
        .Append("  FROM PERSONS P ")
        .Append("  INNER JOIN CITIES ")
        .Append("    ON P.IDCITY = C.ID")
        .Append("  WHERE P.ID = {0}")
        Debug.WriteLine(sb.ToString)
    End With

I have created my own DataAccess class which expands on this and allows me to concatenate queries and adds a space at the end of each line in case I forget to add one (as in your example):

Class DataAccess
    Private _queryString As New StringBuilder(String.Empty)

    Public Sub QryAdd(ByVal query As String)
        _queryString.Append(query.TrimEnd + " ")
    End Sub

    Public ReadOnly Property QryStr As String
        Get
            Return _queryString.ToString.TrimEnd()
        End Get
    End Property
End Class
Community
  • 1
  • 1
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
0

You can do this :

Dim strSQL As String = "SELECT P.NAME, C.ID, C.NAME FROM PERSONS P INNER JOIN CITIES ON P.IDCITY = C.ID WHERE P.ID = {0}"
Dim formattedSQL As String = String.Format(strSQL,your_id)

String.Format will replace the placeholders "{0}" with your_id , your_id is the id of the selected person .