In MySQL if I have multiple queries on one page and I end each query with a ; this will prevent the next query from being ran (accidentally ran). this ensures that only that query is ran.
Is there a similar feature in SQLServer2008? So, If I have multiple queries on one page, is there a character or operator that can be added at the end of a query that stops the query execution, so only that query is ran?
I understand typically only the highlighted query will run, but I have seen the whole page get executed (almost always by some mishap) so I was looking for a way to protect/prevent any mishaps from happening.
EDIT: I am using SQL Server Management Studio (new query page)
thanks
There are various ways to do this. Some methods I've used before are:
Use of RETURN:
Select * From Table Where Foo = 'Bar'
Return
Delete Table Where Foo = 'Bar'
RETURN will end the batch at that point, making it so the first query is run, but not the second.
Use of NOEXEC:
Set NoExec Off
Select * From Table Where Foo = 'Bar'
Set NoExec On
Delete Table Where Foo = 'Bar'
NOEXEC will disable the execution of all sql statements while it is active.
Some good old-fashioned commenting:
Select * From Table Where Foo = 'Bar'
--Delete Table Where Foo = 'Bar'
There are other things you can try using (such as RAISERROR), but in general, the best prevention is to separate your scripts into different files when possible, and to be mindful of what you're executing. Either by way of highlighting, or reviewing the file before you press F5.
If I understand your question correctly, you could place a
RAISERROR('Oops', 18, 1)
between each query. This will halt execution after the first (highlighted) query is run.
Related
I'm trying to insert something to a table and also delete at the same time so my query is like this
$query = mysqli_query($connect,"SELECT * FROM inventory_item WHERE status = 'Unserviceable' OR DELETE * FROM inventory_item WHERE status = 'Available")
or die ("Error: Could not fetch rows!");
$count = 0;
I wanted to insert datas with Unserviceable status and at the same time delete datas with Available status but its not working.
I'm not really familiar with queries and just starting out.
This is not valid SQL syntax.
If you want to issue two queries, one to INSERT and one to DELETE, then you can send them as two separate calls to mysqli_query(). There appears to be an alternate function mysqli_multi_query() that allows multiple statements to be included which you can read about here.
Finally, if you want the two separate queries to execute as a single unit (that is, if one of them fails then neither is executed) then you should research the subject of database transactions, which allow you to execute multiple queries and commit or roll back the entire set of queries as a unit.
I have a fairly basic query:
UPDATE the_table SET col1=[something], col2=[something else] WHERE col1 IS NULL AND col2 IS NULL LIMIT 1;
Immediately after issuing the query, the caller does:
SELECT col3 FROM the_table where col1=[something], col2=[something else];
Unfortunately, concurrent callers are claiming the same row.
I'd rather not do a SELECT FOR UPDATE, because the [select, update, select] would involve three rpcs to the database instead of two (which is bad enough.)
I gather that some dialects of sql allow UPDATE the_table WITH(UPDLOCK), but mine (galera/MySQL) does not. I find it appalling that I'd have to go through this many DB hits to execute such a basic concept. I find that most of my searching efforts end on pages that discuss dialects that DO support UPDLOCK.
Where does it go from here?
Do you have autocommit=1?
Without transactional integrity, some other connection can slip in and change the row before you execute the SELECT.
Note that there could be multiple NULL rows, so the UPDATE may be changing many rows.
Did you check the "rows affected" after the UPDATE? Maybe no rows were changed.
I think that it would be better to either execute all the queries in a transaction or to use a stored proc which will be responsible to make all the select and update stuff and then return back to you the respective data from the last select statement. Having such a flow out of transaction, raises issues as the one you describe. You need to lock the row in order not to allow other callers retrieve "dirty" (not up to date) data.
Here is query
BEGIN;
SELECT NumberRenamed, ... FROM 2_1_paidused WHERE CreditAccount = ? AND ...;
SELECT NumberRenamed, ... FROM 2_1_paidused WHERE DebitAccount = ? AND ...;
COMMIT;`
(... is long list with columns and conditions).
and get SQLSTATE[HY000]: General error.
Removed BEGIN; and COMMIT; and all works as expected without errors.
From my knowledge if more than one SELECT, then need to use BEGIN; and COMMIT; But appears that I am wrong. So, does it mean that it is allowed to use more than one SELECT without BEGIN; and COMMIT;? Or my query is incorrect?
Those are four SQL statements. You don't share any PHP code but the way you display the queries suggest that you launch them at once into a single database call. Apparently, running multiple queries in PDO is quite tricky—no idea if you got it right.
In any case, your transaction code is redundant:
PDO has builtin functions to start and commit transactions. There's no need to run commands manually.
You don't write into the database, thus transactions don't have any purpose anyway.
I'm pretty sure you just need to run your two SELECT queries separately.
Edit: perhaps you're confused with BEGIN ... END. That's an entirely different feature. In MySQL, you can only use it in the body of stored routines.
We are seeing 'interesting behavior with our SQL Sever Database. We have a merge statement which selects a table X. In the match clauses there is a subselect to table X. When we execute the stored procedure from the SQL Server Tools it works fine. But when executed from IPC (an ETL Tool) we get an exception Invalid object name 'X'.
So far nothing special as I understand there can get lots of things wrong with permissions and stuff.
The strange thing: The merge statement is in a try block and in the catch block the error message gets written into the table X via an update statement! How is this possible when Sql Server complains it can't find a table X?
Also everything works fine with another stored procedure which is constructed in the same way (via code generation) but on a different set of tables.
The code looks like this
merge ...
using
(select ...
from dbo.X
where ...
when not matched by target
and not exists (select 1 from dbo.X q2 where ...)
then insert (...
)
values (...
)
when matched and q.ACTION='D'
then delete
when matched AND NOT exists (select 1 from dbo.X q3 where ...)
then update
set
...
OUTPUT $action INTO #l_SummaryOfChanges;
-- Query the results of the table variable.
SELECT ACTION, COUNT(*) AS CountPerChange
FROM #l_SummaryOfChanges
GROUP BY ACTION;
end try
begin catch
update dbo.X
set LAST_ERROR_MSG=ERROR_MESSAGE(), ERROR_COUNTER=ERROR_COUNTER+1
where SYNC_ID=#l_SyncID
end catch
Any ideas what is going on?Invalid object name 'sync$_tabTeiledaten'.
We found it. gbn's question triggered the realization that the usage of X had nothing to do with the exception. In fact on target table of the merge was a trigger which is referencing X but from a different schema without actually specifying the schema.
May somebody will benefit from the way we debugged this shit:
we duplicated X with a new name (Y) and still got the error message saying 'Invalid object name 'X'. At that point we thought we might reference a view or something so ..
we removed all the columns (there where lots of) from the merge statement, except those which where necessary due to Not Null Constraints. The problem persisted
We removed 1 of the branches of the merge statement at a time. The problem persisted.
we removed the complete merge statement. The error was gone. At that point we realized that something fishy might go on with the target table.
On inspection we found the trigger from hell.
I am trying to run an INSERT statement on table X each time I SELECT any record from table Y is there anyway that I can accomplish that using MySQL only?
Something like triggers?
Short answer is No. Triggers are triggered with INSERT, UPDATE or DELETE.
Possible solution for this. rather rare scenario:
First, write some stored procedures
that do the SELECTs you want on
table X.
Then, restrict all users to use only
these stored procedures and do not
allow them to directly use SELECT on table
X.
Then alter the stored procedures to
also call a stored procedure that
performs the action you want
(INSERT or whatever).
Nope - you can't trigger on SELECT - you'll have to create a stored procedure (or any other type of logging facility - like a log file or what ever) that you implicitly call on any query statement - easier if you create a wrapper that calls your query, calls the logging and returns query results.
If you're trying to use table X to log the order of SELECT queries on table Y (a fairly common query-logging setup), you can simply reverse the order of operations and run the INSERT query first, then run your SELECT query.
That way, you don't need to worry about linking the two statements with a TRIGGER: if your server crashes between the two statements then you already logged what you care about with your first statement, and whether the SELECT query runs or fails has no impact on the underlying database.
If you're not logging queries, perhaps you're trying to use table Y as a task queue -- the situation I was struggling with that lead me to this thread -- and you want whichever session queries Y first to lock all other sessions out of the rows returned so you can perform some operations on the results and insert the output into table X. In that case, simply add some logging capabilities to table Y.
For example, you could add an "owner" column to Y, then tack the WHERE part of your SELECT query onto an UPDATE statement, run it, and then modify your SELECT query to only show the results that were claimed by your UPDATE:
UPDATE Y SET owner = 'me' WHERE task = 'new' AND owner IS NULL;
SELECT foo FROM Y WHERE task = 'new' AND owner = 'me';
...do some work on foo, then...
INSERT INTO X (output) VALUES ('awesomeness');
Again, the key is to log first, then query.