4
votes

I am working ServiceStack.OrmLite using MS SQL Server. I would like to execute raw SQL against database but original documentation contains description of how to do it with SELECT statement only. That is not enough for me.

I cant find the way to run anything as simple as that:

UPDATE table1
SET column1 = 'value1' 
WHERE column2 = value2

Using, for example:

var two = db.Update(@"UPDATE table1
    SET column1 = 'value1' 
    WHERE column2 = value2");

Running this expressions with db.Update() or db.Update<> produces uncomprehensive errors like

Incorrect syntax near the keyword 'UPDATE'.

I would like to use raw sql because my real UPDATE expression uses JOIN.

2

2 Answers

6
votes

db.Update is for updating a model or partial model as shown in OrmLite's Documentation on Update. You can choose to use the loose-typed API to build your update statement, e.g:

db.Update(table: "table1", 
  set: "column1 = {0}".Params("value1"), 
  where: "column2 = {0}".Params("value2"));

The Params extension method escapes your values for you.

Otherwise the way to execute any arbitrary raw sql is to use db.ExecuteSql().

1
votes

If it is a SELECT statement and you want to execute using raw sql you can use:

List<Person> results = db.SqlList<Person>("SELECT * FROM Person WHERE Age < @age", new { age=50});

Reference: https://github.com/ServiceStack/ServiceStack.OrmLite#typed-sqlexpressions-with-custom-sql-apis