Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update and select in one query

Tags:

sql

mysql

I found similar questions with correct answers. But they're a bit complicated for me. I just want a simple basic statement.

I have:

string sql = "UPDATE tblPopUp 
                 SET PopUp = 'False' 
               WHERE DisplayNo = 1"

...and:

string sql1 = "SELECT Period  
                 FROM tblPopUp 
                WHERE DisplayNo = 1"

How can I combine them?

like image 275
william Avatar asked Oct 30 '10 04:10

william


People also ask

Can we use update and SELECT together in SQL?

The subquery defines an internal query that can be used inside a SELECT, INSERT, UPDATE and DELETE statement. It is a straightforward method to update the existing table data from other tables. The above query uses a SELECT statement in the SET clause of the UPDATE statement.

Can we use update in SELECT statement?

The UPDATE from SELECT query structure is the main technique for performing these updates. An UPDATE query is used to change an existing row or rows in the database. UPDATE queries can change all tables' rows, or we can limit the update statement affects for certain rows with the help of the WHERE clause.

How do you update a column using SELECT query in SQL?

Col2)) UPDATE CTE SET Col1 = _Col1, Col2 = _Col2; This has the benefit that it is easy to run the SELECT statement on its own first to sanity check the results, but it does requires you to alias the columns as above if they are named the same in source and target tables.


3 Answers

UPDATE tblPopUp  
SET PopUp = 'False', Period = Period  
OUTPUT DELETED.Period
WHERE DisplayNo = 1

For more information about OUTPUT clause please check this post.

like image 190
Subhash Avatar answered Oct 03 '22 21:10

Subhash


You can't.

There's no convention in a SQL UPDATE statement for returning data. And vice versa -- a SELECT statement doesn't write information to a table.

If you've found questions/answers that you feel are similar to what you want, please provide links.

like image 37
OMG Ponies Avatar answered Oct 03 '22 19:10

OMG Ponies


The correct way to do this (now for MySQL 5+), would be with a stored procedure.

like image 41
Lafras Henning Avatar answered Oct 03 '22 21:10

Lafras Henning