Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL "IF @@Rowcount > 0" analog in Sqlite?

I have t-sql insert query to table [foo] (bar_id int primary key autoincrement, bar_name varchar) with text:

INSERT INTO foo(bar_name)
VALUES (@bar_name_new);
IF @@ROWCOUNT > 0
    SELECT bar_id, bar_name
    FROM foo
    WHERE bar_id = scope_identity();

A trigger can modify bar_name field after insert. That's why I need to refresh "bar_name" field. Now I need to do the same at sqlite db. I've wrote this:

INSERT INTO foo(bar_name)
VALUES (@bar_name_new);

 SELECT bar_id, bar_name
 FROM foo
 WHERE bar_id = (SELECT last_insert_rowid());

I can check number of changes in db calling sqlite changes() function. And I know about case statement in sqlite. But how can I tell sqlite that there is no need to do select when changes() returns 0?

like image 993
Coffka Avatar asked May 20 '12 08:05

Coffka


People also ask

What is the use of @@ rowcount?

Data manipulation language (DML) statements set the @@ROWCOUNT value to the number of rows affected by the query and return that value to the client. The DML statements may not send any rows to the client.

What is select @@ rowcount?

Usage. SQL Server @@ROWCOUNT is a system variable that is used to return the number of rows that are affected by the last executed statement in the batch.

How do you give Rowcount in SQL?

The ROWCOUNT Set Function causes the server to stop the query processing after the specified number of records is returned. One may limit the number of records returned by all subsequent SELECT statements within the session by using the keyword SET ROWCOUNT.

How do you get Rowcount?

Counting all of the Rows in a Table. To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.


1 Answers

SQLite's flavor of SQL doesn't have the branch and loop constructs that T-SQL has. Control-flow logic is exercised in the host language.

In your case, you want the sqlite3_changes function. You're going to need it anyway, to decide whether there are any rows to retrieve. Although, as a matter of ease and efficiency, you might as well just execute the query where changes() > 0 if (as I suspect) the query planner is smart enough to return instantly.

like image 57
James K. Lowden Avatar answered Oct 01 '22 22:10

James K. Lowden