Execute raw SQL using ServiceStack.OrmLite - sql

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.

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().

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

Related

Can I use a query parameter in a table name?

I want to do something along the lines of:
SELECT some_things
FROM `myproject.mydataset.mytable_#suffix`
But this doesn't work because the parameter isn't expanded inside the table name.
This does work, using wildcard tables:
SELECT some_things
FROM `myproject.mydataset.mytable_*`
WHERE _TABLE_SUFFIX = #suffix
However, it has some problems:
If I mistype the parameter, this query silently returns zero rows, rather than yelling at me loudly.
Query caching stops working when querying with a wildcard.
If other tables exist with the mytable_ prefix, they must have the same schema, even if they don't match the suffix. Otherwise, weird stuff happens. It seems like BigQuery either computes the union of all columns, or takes the schema of an arbitrary table; it's not documented and I didn't look at it in detail.
Is there a better way to query a single table whose name depends on a query parameter?
Yes, you can, here's a working example:
DECLARE tablename STRING;
DECLARE tableQuery STRING;
##get list of tables
CREATE TEMP TABLE tableNames as select table_name from nomo_nausea.INFORMATION_SCHEMA.TABLES where table_name not in ('_sdc_primary_keys', '_sdc_rejected', 'fba_all_order_report_data');
WHILE (select count(*) from tableNames) >= 1 DO
SET tablename = (select table_name from tableNames LIMIT 1);
##build dataset + table name
SET tableQuery = CONCAT('nomo_nausea.' , tablename);
##use concat to build string and execute
EXECUTE IMMEDIATE CONCAT('SELECT * from `', tableQuery, '` where _sdc_deleted_at is not null');
DELETE FROM tableNames where table_name = tablename;
END WHILE;
In order to answer your stated problems:
Table scanning happens in FROM clause, in WHERE clause happens filtering [1] thus if WHERE condition is not match an empty result would be returned.
"Currently, Cached results are not supported when querying with wildcard" [2].
"BigQuery uses the schema for the most recently created table that matches the wildcard as the schema" [3]. What kind of weird stuff you have faced in your use case? "A wildcard table represents a union of all the tables that match the wildcard expression" [4].
In BigQuery parameterized queries can be run, But table names can not be parameterized [5]. Your wildcard solution seems to be the only way.
You can actually use tables as parameters if you use the Python API, but it's not documented yet. If you pass the tables as parameters through a formatted text string vs. a docstring, your query should work.
SQL example:
sql = "SELECT max(_last_updt) FROM `{0}.{1}.{2}` WHERE _last_updt >= TIMESTAMP(" +
"CURRENT_DATE('-06:00'))".format(project_id, dataset_name, table_name)
SQL in context of Python API:
bigquery_client = bigquery.Client() #setup the client
query_job = bigquery_client.query(sql) #run the query
results = query_job.result() # waits for job to complete
for row in results:
print row

how to update the multiple rows at a time in aspnetboilerplate?

I want to execute the SQL clause like:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Because I want to update multiple rows in database. But I don't know how to implement this.
I have found the solution. Using the extension method GetDbContext of Repository to get the DbContext, then using the DbContext.Database.ExecuteSqlCommandAsync to execute raw SQL.

Update multiple values in an oracle table using values from an APEX collection

I am using APEX collections to store some values and pass them between pages in Oracle Application Express 4.2.3.
I would like to then perform an update statement on a table called "project" with the values from the collection.
My code so far is as follows:
update project
SET name=c.c002,
description=c.c007,
start_date=c.c004,
timeframe=c.c005,
status=c.c009
FROM
apex_collections c
WHERE
c.collection_name = 'PROJECT_DETAILS_COLLECTION'
and id = :p14_id;
where :p14_id is the value of a page item.
However, I am getting the following error:
ORA-00933: SQL command not properly ended
Anyone have any idea on how to approach this?
Thanks!
The UPDATE syntax you are using is not valid in Oracle; it does not allow you to use FROM in the way you are attempting.
The simplest way to do this in Oracle would with a subquery:
update project
set (name, description, start_date, timeframe, status) =
(select c.c002, c.c007, c.c004, c.c005, c.c009
FROM
apex_collections c
WHERE
c.collection_name = 'PROJECT_DETAILS_COLLECTION'
)
WHERE
id = :p14_id
;
Note that if the subquery returns no rows, the columns in the target table will be updated to NULL; this could be avoided by adding a similar EXISTS condition in the predicate for the update. It could also be avoided by using a MERGE statement instead of an UPDATE.
If the subquery returns multiple rows, the statement will throw an error. It looks like tthat should not be the case here.

SQL query using CONTAINS doesn't work on specify keyword

I am writing a simple query in SQL Server:
SELECT *
FROM Table1
WHERE CONTAINS(Column1, 'MY')
but it doesn't return any results. While using like it returns results.
Is there any specific reason why the keyword 'MY' doesn't work?
Update:
If I use other keywords, it works, only the specific 'MY' seems to be that I cannot used. My column is already set into fulltext index. Also for performance purposes I prefer to use CONTAINS.
you could do something like
select * from Table1 where Column1 like '%MY%'
When you use linq you can use the statements like you use in C#. It will be translated to SQL, a language which database can execute. So, try something like this:
string sql = "SELECT * FROM Table1 WHERE Column1 like #Column1";
And in your command, try to add parameters to replace the #Column1
command.Parameters.AddWithValue("#Column1", "%MY%");
The % char, represents anything. So, if you want to do a command like StartWith like we do from string, just use MY%.

returning emptystring if columnn name not exists

I have a very simple select statement like
SELECT Column-Name
FROM Object
WHERE ID = 123
where the Column-Name is dynamically generated. Is there a possibility to get an empty string if column not exists?
This is a huge hack for SQL Server
SQL is batch based: when submitted to the database engine, the whole batch is parse and a plan compiled. If a column or object does not exist, you'll get an error.
You can test the metadata to see if it exists (COLUMNPROPERTY) then use EXEC to have the SELECT in an separate batch
IF COLUMNPROPERTY(OBJECT_ID('Object'), 'Column-Name', 'ColumnID') IS NOT NULL
EXEC ('SELECT Column-Name FROM Object WHERE ID = 123')
ELSE
SELECT '' AS Column-Name;
Personally, I'd never expect this to be in production code or running on my database servers.
Why not do a desc object or something similar and validate if the column name exists before firing the query?
Otherwise you will end up doing funny things to work around the sql error