MySQL to SQL Server select statement - mysql

I am converting mysql sprocs to SQL Server. I've come across a select statement in mysql that I don't quite understand what it's doing and my google-fu/so-fu has failed me. Here is the gist of it:
SELECT AccountType = dbo.functionToGetAccountType() FROM AccountLookup
I don't have the ability to debug the original mysql. I do know that the function only returns a single value.
Is the mysql statement assigning a default value to 'AccountType' in the event there are no rows in the AccountLookup table?
Thanks for your time.

The select statement is executing the function dbo.functionToGetAccountType() and aliasing the column as AccountType. It could be re-written as:
SELECT dbo.functionToGetAccountType() as AccountType
FROM AccountLookup

Related

My SQL Syntax error for multiple commands in one query, working for each command running separately

I'm trying to run the following MySQL command:
USE database_name;
DROP TEMPORARY TABLE IF EXISTS only_with_balance;
DROP TEMPORARY TABLE IF EXISTS keys_to_match;
CREATE TEMPORARY TABLE only_with_balance as (
SELECT
*
FROM
transactions t
WHERE
t.balance is not NULL
and (t.transaction_status_id = 4 or t.transaction_status_id = 5)
and (t.date between "2022-05-01" and "2022-08-24" )
);
But I'm getting a syntax error while trying to run the all the commands at once.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DROP TEMPORARY TABLE IF EXISTS only_with_balance;
DROP TEMPORARY TABLE IF EXIST' at line 2
When I run each command separately, the result is the expected.
Can someone help me here?
What am I forgetting?
In MySQL, by default the query interface only allows one SQL statement per call.
There's an option to enable multi-query per call, but it must be set at connect time. Some MySQL connectors do this by default, or allow it as an option, but some do not. You didn't say if you're writing code or if you're submitting this set of queries through a client (though you tag the question 'dbeaver' you don't say anything else about that). So I can't guess what interface you're using for these queries.
Anyway, there's no advantage to using multi-query. The default mode is one SQL statement per call. That's what I do.
Using the default mode of a single SQL statement per call has some advantages:
Supports prepared statements and bound parameters (you can't run multiple statements in a single prepare call, even if you enable multi-query).
Simplifies processing errors and warnings.
Simplifies processing result sets.

mysql) select values if table exists

I'm trying select all values if such table exists. If it doesn't exist, just leave it.
I'm trying to do this only in one MYSQL code. Not with the help of python or something.
SELECT CASE WHEN (SELECT count(*)
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = '{db0}' AND TABLE_NAME = '{table0}')=0
THEN 'None' ELSE (SELECT MAX({colname}) FROM {db0}.{table0}) END;
If i inject existing table name on it, it works well.
But if not , it shows the error sign that saying such table doesn't exist.(Table 'corps.060311' doesn't exist)
What should I do?
This cannot be achieved using a simple query because MySQL analyses the query as a whole before performing it: it is not a procedural language and the queries are never executed line by line.
To do what you want to do without help of any other language, you must use stored procedures: https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html
So the first step is to add a new FUNCTION in your database that will contain the "if table exists" part (see https://dev.mysql.com/doc/refman/8.0/en/if.html for if statements) and will return the desired value based on the schema, table, and column provided as strings in input of the function.
Then you can use the FUNCTION in any query in your database.

Using EXEC() AT [Linked Server] for Insert data from local server

let me first explain a little abot my setup before letting you know the issue Im dealing with:
I have two database servers: SQL 2008 and MySql. I have a procedure in SQL that first, deletes a table in MySql and then populates it with some data from the SQL itself. For both actions im using OPENQUERY. But, as you know, it doesnt know support large data. It becomes really slow eventhou for truncating the table in MySql (it was taking like 14 minutes to delete 60k rows... insane!).
So i found out i could use this syntax for truncating:
EXEC ('TRUNCATE TABLE table_name') AT LINKEDSERVER
But i havent been able to find the syntax for inserting the results of the SQL table to my MySql table thru this. It works correct when I insert static data, like this example:
EXEC ('INSERT INTO table_name (row1, row2) VALUES (value1, value2)') AT LINKEDSERVER
But I want to insert the results from a SQL, as I said, something like this:
EXEC ('INSERT INTO table_name (row1, row2) SELECT r1, r2 FROM SQL_DB.sql_table_name') AT LINKEDSERVER
I bet that i cannot do it because in that syntax, Im executing the exec in the MySql server and the SQL table doesnt exist there. So how can i referrence my SQL table inside the "EXEC() AT" syntax?
Thank you.
you have to use "OPENQUERY" to do this - see
https://learn.microsoft.com/de-de/sql/t-sql/functions/openquery-transact-sql?view=sql-server-ver15
You can also use this:
INSERT INTO [LinkedServer].Database.Schema.Table(Attributes)
From
Select (attributes) from Database.Schema.Table as TableAlias

Can I check if a table exists before join?

I have the following problem. I have Table A and would like to join to table B if table B exists. Can this be done? I am only writing SQL in WorkBench to try achieve it.
I am aware I cannot use the EXISTS option as I have tried typing it out but it prompts for an error.
Any suggestions would be greatly appreciated.
Thanks.
I managed to do this using EXECUTE, so using a query that is only prepared at runtime:
SET #sqlCommand = IF(
EXISTS (SELECT column_name FROM information_schema.columns WHERE table_schema = '{{yourschemaname}}' AND table_name = '{{yourtablename}}' AND column_name = '{{yourcolumnname}}'),
'SELECT \'Yes! Good to go!\' as ColumnExists',
'SELECT \'Nope!\' as ColumnExists');
PREPARE executable FROM #sqlCommand;
EXECUTE executable;
Note that the two selects at the center (Yes!/No!) are the custom statements that are to be executed conditionally. So if the column exists, the first command is executed (select 'yes!'), otherwise the second one (select 'nope').
I got the hint from this discussion here.. have a look if you're looking for the MSSQL equivalent: https://ask.sqlservercentral.com/questions/97579/check-if-table-exists-in-join.html
Data manipulation language statements are typically written for a specific schema; you are assumed to know what the schema looks like when you issue the statement. So you don't generally have the capacity to ask whether a particular schema object exists or has a particular structure. You could however write a stored procedure that did different things depending upon the schema. You have the ability in a stored procedure to use conditional statements and to look in INFORMATION_SCHEMA.

Update statement followed by select MySQL

I am storing cache information from the cache server if application version is matching else I need to set cache details as NULL.
Currently I am doing it like this
UPDATE
cache_table
SET
_data = NULL
WHERE _id = id AND _app_version != "current_version"
Followed by select query
SELECT
_data
FROM
cache_table
WHERE _id = id AND _app_version == "current_version"
Is there a way I can do required update and select in one query without firing two query ?
Note: I don't want to use MySQL procedure. No specific reason but don't want to store application logic in DB so I can easily change database application.
Generally UPDATE and SELECT are two distinct operations. The only way to combine them is with a stored procedure as you identify.
I dont believe in MySQL there is a built-in way to do this. However, just FYI this can be done in SQL Server using OUTPUT clause:
http://msdn.microsoft.com/en-us/library/ms177564.aspx