0

I have a string coming from database.

var query = @"Select SKUs from dbo.Order order by OrderDate OFFSET {skip} ROWS FETCH NEXT {take} ROWS ONLY"

This string is coming from database directly, so I dont have this string formed in code. I want to use $ interpolation to replace them

var skip = 0;
var take = 200;
query = $query

Is there any way I can do this? I know I can use replace or string.format but just curious if we can do this.

2
  • 2
    Why not use a parameterized query and eliminate any possibility of errors or SQL injection? Commented Apr 18, 2022 at 12:05
  • 1
    Echoing @PanagiotisKanavos, reading a query (ie "code") from an external source then executing it is a very dangerous idea. Commented Apr 18, 2022 at 12:05

1 Answer 1

2

The $"" syntax is only for string literals.

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions.

$ - string interpolation (C# reference)

String literals only exist in the source code. Anything you read from a database is a string object and cannot be a literal.

As you mentioned, you need to use conventional methods to manipulate the string's data (string.Format, regex, etc).

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

3 Comments

As if you would have placed {0}, {1} in database we could have use string.format without having string formed in code
@Manjay_TBAG what you ask is a bad idea in the first place. It leaves you open to SQL injections or simple coding errors. Don't construct SQL queries from strings (that includes string formatting) if possible
@Manjay_TBAG as for without having string formed in code but that's exactly what you're doing. String interpolation is still string construction in code. If take contained 1 ROWS ONLY; DROP TABLE Students;-- you'd end up with a query that dropped a table

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.