0

What I want to achieve is, from this:

string[] QueryString = new string[]{
        "Column1",
        "Column2"
    };

Create this:

SELECT  Column1,Column2
FROM    SomeTable

I know that I could do a concat but that's not a very clean way to doit.

3 Answers 3

2

I know that I could do a concat but that's not a very clean way to do it.

Seems pretty clean to me:

string sql = "SELECT " + string.Join(", ", QueryString) + " FROM SomeTable";

Although you're susceptible to SQL injection attacks:

string[] QueryString = new string[]{
        " * FROM SomeTable; DROP TABLE SomeTable; --"
    };

So ONLY do this if you have complete control of the column names that can be used (e.g. populated from the table metadata).

Sign up to request clarification or add additional context in comments.

2 Comments

I have full control of column names.
@skmasq Also, you probably want to safely quote the identifiers, e.g. SELECT [Column1], [Column2] FROM [SomeTable], otherwise a column name like my column would cause errors.
0
Declare @qtext varchar(max) = 'select '+column1+ ' , '+column2+ ' from sometable ' 
Exec(@qtext)

Comments

0

You could use String.Format

http://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx

String query =
String.Format("SELECT {0}, {1} FROM SomeTable", QueryString[0], QueryString[1]);

Although, as always when constructing sql queries, be aware of sql injection attacks.

2 Comments

this will not work when there is more than two columns
@PranayRana is right, it's dynamic array, thus tag dynamic :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.