The correct way to format an SQL query inside a C # application

I have a console application in C # that creates a bunch of queries on a database server.

I often need to modify SQL and just simply copy / paste SQL from my SQL editor into C # source code without having to reformat SQL every time.

Currently, SQL is on the same line ... as shown below:

OleDbDataAdapter da_ssm_servers = new OleDbDataAdapter(@"SELECT * FROM mytable ORDER BY Server;", connSSM); 

SQL is much longer than above, with lots of JOINS tables, etc.

I would like to keep the formatting, but really don't want to go back and add quotes around each line, etc.

If anyone has any recommendations and examples, this will be appreciated.

+4
source share
4 answers

I do it like this:

 string sql = @" SELECT * FROM mytable ORDER BY Server"; OleDbDataAdapter da_ssm_servers = new OleDbDataAdapter(sql, connSSM); 
+7
source

My recommendation would be to stay away from special requests, for example, you use and use stored procedures . This will separate your design and also limit your calls to the name of the stored procedure and possibly parameters.

But if you have to use ad hoc requests and then the prefix with @ , and you can span multiple lines without having to surround each line in quotation marks.

+2
source

As long as you use the @ syntax, you can just have multiple lines of the SQL interval.

for instance

 string sql = @"select colA, colB, colC from tableX inner join tableY on tableX.colA = tableY.colA where colB > 20;" 
0
source

It seems that your code should work fine. When you start your line with @, you use a shorthand line. Line breaks and formatting are preserved, and you do not need to insert each line in quotation marks. You just need the final quote.

0
source

Source: https://habr.com/ru/post/1390292/


All Articles