I have an sql query that delete some files at table
I'm running it using EF
string comando = $" delete from MyTable where IdProduccion = '{idProduccion}'";
int res = context.Database.ExecuteSqlCommand(comando);
if (res < 0)
throw new Exception("....")
Some times it returns 0 another times returns 1 or another int, searching trough documentation I have this
Return Value
Type: System.Int32
The result returned by the database after executing the command.
But What exactly means that integer ?
If I have a result other than 0, an error happens at Db?
int res = context.Database.ExecuteSqlCommand(comando);
The ExecuteSqlCommand returns the total number of rows affected by DELETE action. For example, as your delete action result if 2 rows are deleted, it should return as 2.
If I have a result other than 0, an error happens at Db?
No, don't use the return value for checking the some kind of errors. If an error occurs in SQL Server, It throws an error and It could be better to use try/catch block to handle errors.
Related
I use the ROWCOUNT field in SYSTABLES to get fast the rowcount of all my tables from a .NET App using Oledb (i don't want to use a query to get it becasue it takes too much time on big tables).
The problem is: after deleting rows from the table, that ROWCOUNT number in SYSTABLES is not updated. I tested some commands and even found that running ROWCOUNT TABLENAME in SqlTalk works and is very fast, but if i try to call that as a query from .NET using OLEDB it's returning nothing, sample code:
using (var connection = ConnectionFactory.CreateConnection(NombreBaseModelo))
{
using (OleDbCommand cmd = connection.CreateCommand())
{
foreach (Tabla ot in LstTables)
{
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 5000;
cmd.CommandText = "ROWCOUNT " + ot.NAME;
var sRet = cmd.ExecuteScalar();
ot.ROWCOUNT = int.Parse(sRet);
}
}
}
Is there any way to tell SqlBase to update Rowcount for each table in systables?
Or as alternative, is there any way to make this code work?
Thanks!
The systables.rowcount only gets updated when an update statistics is done, so it's not guaranteed to be accurate, until you execute 'Update Statistics on table ' + ot.NAME;
Then it is .
Probably not what you want when quickly counting rows.
Does your 'ot.NAME' variable have a table owner included ? usually its 'SYSADM.'
Have you checked the value returned in 'sRet' , as maybe its 'int.Parse(sRet)' that is failing.
Otherwise create an index on the PK and execute a COUNT(*) . Should be as fast as ROWCOUNT anyway if the index is being used .
Alternatively, write a SQLBase function or stored proc that just executes the ROWCOUNT command natively and returns the correct count ( as per SQLTalk ), and call that from your , Net app
I have a query that is related to this topic:
https://developer.jboss.org/thread/277610
Prior to reaching the comma separated values stage, the values are actually stored as a blob.
There is a function fetchBlobtoString(Blob, string, VARIADIC start_end integer) returns String that actually takes the blob input and then converts to comma separated values as seen on the post.
The issue with this is string is limited to 4000 characters, hence it will decimate the data and not all values show up. What would be the best way to extract the values that are double and convert it to rows similar to the post.
Would converting it in to an object instead of string improve performance using following function as an example:
fetchElementValueFromBlob(protobufBlob Blob, origName string) returns object
I have tried iterating items in blob using getItem function, add to temp table, but its slow and I get following error If i go more that 15-20 iterations:
Error: TEIID30504 Remote org.teiid.core.TeiidProcessingException: TEIID30504 petrelDS: TEIID60000 javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/petrelDS
SQLState: 50000
ErrorCode: 30504
BEGIN
DECLARE integer VARIABLES.counter = 0;
DECLARE integer VARIABLES.pts = 100;
WHILE (VARIABLES.counter < VARIABLES.pts)
BEGIN
select wellbore_uwi,getItem(fetchBlob(data, 'md'),VARIABLES.counter) INTO TEMP from DirectionalSurvey where wellbore_uwi='1234567890';
VARIABLES.counter = (VARIABLES.counter + 1);
END
SELECT TEMP.wb_uwi,TEMP.depth FROM TEMP;
END
If I remove the getItem() function, the error goes away.
I want to check if something is present in my database before saving it in order to avoid key duplicate errors. I'm using Play! 2.2.6 with anorm and Postgresql 9.3.
So I wrote a little function (I omit the errors check):
def testIfExist(fieldName: String, value: String): Boolean = {
DB.withConnection { implicit connection =>
SQL( """SELECT exists(SELECT 1 FROM events where {fieldName}={value} LIMIT 1)""")
.on(
'fieldName -> fieldName,
'value -> value
).execute()
}
}
But it always return true although my database is totally empty.
So I tested to replace
SELECT exists(SELECT 1 FROM events where {fieldName}={value} LIMIT 1
by
SELECT exists(SELECT 1 FROM events where name='aname' LIMIT 1
and it still always return true...
I also tested the same query directly in psql and the response is what I except : false...
execute returns true if anything was returned in the result set. In this case it will be 0 or 1. It will only return false if the query was an update (returns no result set). You need to use as with a ResultSetParser to parse the results.
There's another problem with this code as well. You can't supply column names in prepared statements. {fieldName}={value}. This will get turned into a string comparison, which will probably always be false. Instead, you can use string interpolation to insert the field name into the query. Though be wary, fieldName should be be from user defined input as it is vulnerable to SQL injection. (Your users shouldn't need know about your columns anyway)
SQL(s"SELECT exists(SELECT 1 FROM events where ${fieldName} = {value} LIMIT 1)")
.on("value" -> value)
.as(scalar[Boolean].single)
Have been bug hunting all day and located the following unexpected behaviour with sqlaclhemy (flash-sqlalchemy to be precise).
The code is
actionId = 1
DataLists.query.\
join(Actions, actions.action_id == DataLists.action_id).\
filter(Actions.action_id == actionId).\
update({DataLists.dt_cancelled: datetime.utcnow()})
#Updates ALL DataLists!
The query (without the update) returns 1 record, yet ALL records are updated.
#testing
rows = DataLists.query.\
join(Actions, actions.action_id == DataLists.action_id).\
filter(DataLists.action_id == actionId).\
all()
print("rows: {}".format(len(rows))) # outputs 1
From what I understand, the update works on the returned rows. Which is not happening, so I must be missing something here.
I have tried to get a copy of the SQL statments, but the update statement doesn't appear to work like a normal query, so
sql = DataLists.query.\
join(Actions, actions.action_id == DataLists.action_id).\
filter(Actions.action_id == actionId).\
update({DataLists.dt_cancelled: datetime.utcnow()})
print(str(sql))
doesn't work, and returns that 114 rows were updated
Now it turns out that the join isn't infact needed and the query can be written as
DataLists.query.\
filter(DataLists.action_id == actionId).\
update({DataLists.dt_cancelled: datetime.utcnow()})
#testing
rows = DataLists.query.\
filter(DataLists.action_id == actionId).\
all()
print("rows: {}".format(len(rows))) # outputs 1
strangely (to me anyway) this now works as expected. Just a single row is updated.
So the issue is with the join. But each DataList is joined on a foreign key 'action_id', this is unique and does not ever return multiple rows.
So does the update command not work with a join? Or is there a glaring bug in the above code I am blind to?
I have a stored procedure in my db that looks like this:
IF EXISTS (SELECT * FROM Table1)
BEGIN
-- select statement
END
I am using this procedure to check if there is any data inside table1. Table1 is used as a queue on database side.
In my C# application I am using the entity framework to execute this stored procedure. Method Looks like this:
using (DatabaseEntities db = new DatabaseEntities())
{
var result = db.ALL_GET_JOBS();
if (result == null)
{
Console.WriteLine("No new jobs");
}
else
{
Console.WriteLine(string.Format("received {0} new jobs", result.Count()));
}
}
When I execute to procedure I get an exception telling me that one of my defined columns doesn't exists within the result. Yeah, because the procedure is returning 0. The exception is thrown before I reach the if statement.
I already tried adding .DefaultIfEmpty(null) or .FirstOrDefault() to the call of the procedure, but as far as I can say, the error occurs during the evaluation of the result.
Does any one of you have an idea how to handle a procedure that is returning 0 instead of a result set in entity Framework?
bg
Christoph
I think you should change your sp or create a new one with Count function:
SELECT Count(*) FROM Table1
with this your resul is always a number (0 or greater).
I konw it's a workaround, but have you tried having the stored procedure always return the same?
Something like:
SELECT Field1, Field2 FROM Table1
You can just check if result.Count() == 0 instead of result == null.