convert mysql stored procedure to mssql - mysql

I need to used dynamic order query in mysql and i have successfully achieved that through string concatenation in mysql as follows:
set #stmt_text := concat('select * from abc order by ',sorder);
prepare stmt_handle from #stmt_text;
execute stmt_handle;
deallocate prepare stmt_handle;
i need a similar way to convert this in mssql
Any ideas??

Yes, just run it like this:
execute ('select * from abc order by ' + #sorder);
But don't forget that you need to verify the sorder variable if you get it through user input (to stop sql-injections)

Related

MySQL - create a table with all of the fields that two tables have [duplicate]

I have to convert a MSSQL stored proc that passes a varchar that is a query:
INSERT INTO Results
EXEC (#Expresion);
This isn't working. I'm pretty sure that EXEC and EXECUTE aren't MySQL commands, but CALL doesn't work either.
Does anyone know if it's even possible to have something like JavaScript's eval function for MySQL?
I think you're looking for something like this:
SET #queryString = (
SELECT CONCAT('INSERT INTO user_group (`group_id`,`user_id`) VALUES ', www.vals) as res FROM (
SELECT GROUP_CONCAT(qwe.asd SEPARATOR ',') as vals FROM (
SELECT CONCAT('(59,', user_id, ')') as asd FROM access WHERE residency = 9
) as qwe
) as www
);
PREPARE stmt FROM #queryString;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #asd = NULL;
This is the SQL equivalent of eval(my_string);:
#Expression = 'SELECT "Hello, World!";';
PREPARE myquery FROM #Expression;
EXECUTE myquery;
Basically I combined the existing answers, neither tells you how to do eval exactly.
If you want to add parameters, you can use this:
#username = "test";
#password = "asdf";
#Expression = 'SELECT id FROM Users WHERE name = ? AND pass = ?;'
PREPARE myquery FROM #Expression;
EXECUTE myquery USING #username, #password;
And to answer the original question exactly:
#Expression = 'SELECT "Hello, World!";'
PREPARE myquery FROM #Expression;
INSERT INTO Results
EXECUTE myquery;
Note that the PREPARE ... FROM statement wants a session variable (prefixed with #). If you try to pass a normal variable, it will throw its hands up in the air and it just won't care.
EXECUTE is a valid command in MySQL. MySQL reference manual
The EXECUTE MySQL command can only be used for one prepared statement.
If case you want to execute multiple queries from the string, consider saving them into file and source it, e.g.
SET #query = 'SELECT 1; SELECT 2; SELECT 3;';
SELECT #query INTO OUTFILE '/tmp/temp.sql';
SOURCE /tmp/temp.sql;

Set MySQL Column Alias to a Calculated Date

I'm looking to do something like this:
select data AS curdate() from table;
so the resulting table would look like:
2013-04-26
data 1
data 2
data 3
I can't figure out the syntax, but it must be possible?
I've tried it without quotes of any kind, which returns an error. Single quotes and back ticks both return the SQL itself as the column header.
That's an unusual requirement, but if you insist, you'd have to use dynamic sql.
SET #curdate = CURDATE();
SET #sql = CONCAT('SELECT whatever AS "', #curdate, '" FROM whatever');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
An alias is considered an identifier and cannot be assigned to a function without the use of dynamic SQL. It would break referencing such as:
SELECT *
FROM (SELECT 1 AS curdate()) a

How can you disable result output for the mysql EXECUTE command in workbench

I'm trying to use a prepared statement in mysql workbench in a cursor. The cursor works on a very big data set so it is executed many times. Every time a new result is shown for the EXECUTE step. This results eventually in mysql workbench crashing because of too many open result windows.
In the cursor I do something like this:
PREPARE stmt2 FROM #eveningQuery;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
Normally I use stuff like
set aVar = (EXECUTE stmt2);
to silence the query but EXECUTE doesn't work like that.
Does anybody know how you can disable the output for the EXECUTE command in mysql?
Note: I understand how i can retrieve the data in a variable, however what I want to prevent is that it is displayed in the results overview like this
This will make mysql-workbench crash when looped too much.
edit because it was asked an example of the #eveningQuery.
SET #eveningQuery = CONCAT('select #resultNm := exists (select idSplitBill from tb_SplitDay where idSplitBill =', idSplitBillVar, ' and ', #columnNameEv ,' = 1 and softdelete = 0)');
idSplitBillVar = the id coming from the cursor.
#columnNameEv = a column that i am filling in variably.
I added this info because it was asked, however it doesn't really matter in my opinion because the question still stands even with the most simple query. When you execute a prepared statement, you will get a output result. I just want to disable this behaviour.
The query you use creates new result-set, and GUI client show it (...many times) -
SELECT #resultNm:=EXISTS(
SELECT idSplitBill FROM tb_SplitDay
WHERE idSplitBill =', idSplitBillVar, ' AND ', #columnNameEv ,' = 1 AND softdelete = 0
)
You can rewrite this query, and result-set won't be created -
SELECT EXISTS(
SELECT idSplitBill FROM tb_SplitDay
WHERE idSplitBill =', idSplitBillVar, ' AND ', #columnNameEv ,' = 1 AND softdelete = 0
)
INTO #resultNm

how to configure the table at runtime in mysql query

people know that we can use if statement to configure a query in the select statement like this
select if(var=1,amount,amount/2) from mytable;
But what if I want to achieve something like this:
select amount from if(var=1,mytable1,mytable2);
Is there any way to configure the table at run time?
SELECT amount FROM mytable1 WHERE #var = 1
UNION
SELECT amount FROM mytable2 WHERE #var = 0
UPD: Here's what MySQL EXPLAIN looks like for the part of the query which has a condition evaluating to FALSE:
Note the Impossible WHERE part. MySQL recognizes that the expression in WHERE is constantly evaluating to FALSE, so it doesn't even try executing the query. Hence, no performance overhead when using this approach.
(Upgrading to an answer)
Where did var come from?
If it's a variable in another language, you could test it in that other language and then construct different SQL as appropriate:
$sql = "SELECT amount FROM " . ($var = 1 ? "mytable1" : "mytable2");
If it's a user variable in SQL, you could similarly use an IF statement around the two alternative SELECT statements:
DELIMITER ;;
IF #var = 1 THEN
SELECT amount FROM mytable1;
ELSE
SELECT amount FROM mytable2;
END IF;;
DELIMITER ;
If it's anything else (like a field from your tables), then your question doesn't make a great deal of sense.
Based on the mysql manual pages, it appears you cannot do this with the traditional syntax.
"User variables are intended to provide data values. They cannot be used directly in an SQL statement as an identifier or as part of an identifier, such as in contexts where a table or database name is expected, or as a reserved word such as SELECT."
- [http://dev.mysql.com/doc/refman/5.6/en/user-variables.html][1]
The exception to this is that you can assemble a prepared statement, but is probably not a better solution for most programming tasks. It would be better to leave the sql string generation to the language invoking mysql.
But, if you are doing this as part of a "sql only" task, like an import, this seems to be the approach you must take.
SET #s = CONCAT("SELECT * FROM ", if(true, "table1", "table2"), " LIMIT 1");
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #s = CONCAT("SELECT * FROM ", if(false, "table1", "table2"), " LIMIT 1");
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Using variables as OFFSET in SELECT statments inside mysql's stored functions

I'm quite new to subject of writting stored function for mySQL database, hence i'm not sure if what i'm trying to do here is possible at all.
I need a function that will return a column from random row from a table. I don't want to use ORDER BY RAND() method to do that, rather i would do this like this:
DECLARE MAX_COUNT INT DEFAULT 120000;
DECLARE rand_offset INT;
DECLARE str_rnd_word VARCHAR(255);
SET rand_offset = FLOOR((RAND() * MAX_COUNT));
SELECT word INTO str_rnd_word FROM all_words LIMIT 1 OFFSET rand_offset ;
RETURN str_rnd_word;
MySQL throws an error upon creating function with body like that. But when I use hard-coded number as OFFSET it works just fine.
Can someone shed some light on the subject please.
I'm running MySQL 5.0.45 on windows box.
Thanks
In MySQL before 5.5, you can't put a variable into the LIMIT clause in MySQL stored procedures. You have to interpolate it into a string and then execute the string as a dynamic query.
SET rand_offset = FLOOR(RAND() * (SELECT COUNT(*) FROM all_words));
SET #sql = CONCAT('SELECT word INTO str_rnd_word FROM all_words LIMIT 1 OFFSET ', rand_offset);
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;