Storing query Results into a Variable to use later - mysql

Like the title says, i am trying to store the results of a query in a variable so that i can use it in another query that would join them. I have been trying to do this using the INTO santex as it describes it on google. This is what i am entering:
mysql> select Name, Type, Region from table1 union select Name, Type, Region from Table2 into #temp1;
However, with this, i am getting this error:
ERROR 1222 (21000): The used SELECT statements have a different number of columns
Which does not make sense as the Select statement has the same number of columns. So i figure maybe its my variable, so i remove the # and tried it again, but i got this error:
ERROR 1327 (42000): Undeclared variable: temp
So now im at a lost, what am i doing wrong? I am following the syntax that is describe on several wikis on google but with no luck.

You can create a temporary table like this.
mysql> CREATE TEMPORARY TABLE SalesSummary (
-> product_name VARCHAR(50) NOT NULL
-> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
-> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
-> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
They have great tutorials here:http://www.tutorialspoint.com/mysql/mysql-temporary-tables.htm

You need to set your variable in your SELECT statement, and not after.
See: http://dev.mysql.com/doc/refman/5.0/en/example-user-variables.html

Related

Check if a field exists and it's not null

I need to fetch a value from a table with three possibilities: 1) The field exists and it's not null, so it returns the value of the field 2) the field exists but it's null, so it returns is-null-string 3) The field doesn't exists, so it returns not-existing-string
I am trying to run this query but I get this error message #1054 - Unknown column 'm.my_field' in 'field list'
SELECT if (exists(SELECT *
FROM information_schema.COLUMNS
WHERE TABLE_NAME = 'my_table' AND COLUMN_NAME = 'my_field'
), IFNULL(m.my_field, 'is-null-string'), 'not-existing-string'
) AS my_field,
m.*
FROM my_table m
Any idea how can I get it done in mysql 5.6?
What you are looking for is DESCRIBE:
DESCRIBE my_table;
Look at the result to see if your field exists. Note, you don't want this code to be in your application. You need to know your table fields to run queries. You might only use this to generate some boilerplate code.

Why does this table name require back-ticks?

I am seeing a curious name dependency in the following MySQL table definition. When I code the table as shown, it seems to break MySQL. When I perform "select * from dictionary_pair_join" from MySQLQueryBrowser, the status bar says "No resultset returned" -- no column names and no errors. When I insert a row into the table, the status bar says "1 row affected by the last command, no resultset returned", and subsequent selects give the same "No resultset returned" response.
When I enclose the tablename in backticks in the "select" statement, all works fine. Surely there are no mysql entities named "dictionary_pair_join"!
Here is the table definition:
DROP TABLE IF EXISTS dictionary_pair_join;
CREATE TABLE dictionary_pair_join (
version_id int(11) UNSIGNED NOT NULL default '0',
pair_id int(11) UNSIGNED default NULL,
KEY (version_id),
KEY (pair_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Here is the broken select statement:
select * from dictionary_pair_join;
Here is its working counterpart:
select * from `dictionary_pair_join`;
Why are backticks required in the select statement?
Update: This also fails in the Python mysqldb interface, which is why I started looking at it. I can put the backticks into my Python "select" generators, but I was hoping this was some stupid and easily-changed nit. I suppose I can also find a different name.
I've uprated the comments from Quassnoi and Software Guy, together they've persuaded me that it's just a bug in mysql/mysqldb/mysqlquerybrowser.
I changed the table name (to "dictionary_pair_cons") and the problem went away, in both the query browser and mysqldb.

Cannot access temporary tables from within a function

I would like to get count of specific records. So my query will look like the following...
SELECT
ID,
NAME,
(SELECT...) AS UserCount // Stmt1
FROM MyTable
The issue is that, 'Stmt1' is a complex statement and it cannot be written as innerquery.
Well, I can use functions, but the statement includes 'CREATE TABLE' so I get the following error message
Cannot access temporary tables from within a function.
What is the best way to accomplish the task ?
You can use user defined table type to solve your problem.
You just create a table variable like
CREATE TYPE [dbo].[yourTypeName] AS TABLE(
[columeName1] [int] NULL,
[columeName2] [varchar](500) NULL,
[columeName3] [varchar](1000) NULL
)
GO
and you can declare this table variable in your function like
CREATE FUNCTION [dbo].[yourFunctionName]
(
#fnVariable1 INT ,
#yourTypeNameVariable yourTypeName READONLY
)
RETURNS VARCHAR(8000)
AS
BEGIN
SELECT .................
FROM #yourTypeNameVariable
WHERE ........
RETURN #r
END
On your procedure you can declare your table type like
DECLARE #yourTypeNamevaribale AS yourTypeName
And you can insert values to this table like
insert into #yourTypeNamevaribale (col,col,..)values(val,val,..)
pass this to your function like
dbo.yourFunctionName(fnVariable1 ,#yourTypeNamevaribale )
please go for this method, thank you
Yes you can not use #temp table.
As you are using SQL Server 2008, why don't you use table variable instead of #temp tables?
Give it a try.
I came across this post as I started using table variables and switched to temporary tables for performance reasons only to find temporary tables couldn't be used in a function.
I would be hesitant about using table variables especially if you are playing with large result sets, as these are held in memory. See this post...
http://totogamboa.com/2010/12/03/speed-matters-subquery-vs-table-variable-vs-temporary-table/
Other alternatives would be..
Extracting the temporary table result into another table function.
Converting the code into using sub-queries
In 99,99% of cases there is no need for any tricks with temp tables or subqueries, but use aggregation functions like COUNT, SUM or AVG in combination with OVER clause and (often) PARTITION BY.
I am not sure what the OP tried to achieve but I assume that the UserCount is somehow related to the values in MyTable. So there must be a way to join MyTable to whatever table that produces UserCount.
The most simple example is to show all users and the total number of users
SELECT id
, name
, user_count = COUNT(*) OVER()
FROM MyUsers

MySQL- Stored Procs- Weirdness when trying to use an output parameter

To be honest, I'm feeling pretty stupid right now. But this simply isn't working.
Scenario
I have a stored procedure that includes an output parameter. I'm trying to SELECT a value INTO that parameter. This seems simple, but it continues giving me faulty results. I've checked many online sources, and I'm certain that I'm trying to do it properly.
Code
DELIMITER //
CREATE PROCEDURE `spGetId`(
IN ParamA VARCHAR(32),
OUT OutputId INT
)
BEGIN
SELECT `id` INTO OutputId
FROM `Table`
WHERE `column_a` = ParamA;
END//
CALL spGetId('foobar', #Bloop)//
SELECT #Bloop//
Results
I have two rows in this table, their IDs being '1' and '2'. The result I get back is '31', whether the SELECT statement matches anything or not.
I have tried many variations, including removing the WHERE clause entirely and having the SELECT return a COUNT(1) into the parameter (which gives me a result of '32', despite there being only 2 rows), and I have tried "declaring" the #Bloop variable before using it in the sproc call by using SET #Bloop = 0.
If you have any insight on why this is happening, and what I can do to make it return the proper value, I would be much obliged. Also, if you can show me how to achieve the same desired result using a Stored Function instead, with a return value, I'd appreciate that even more! My desired approach is using a stored function, but I had similar problems with that, then gave up and tried using a stored proc, only to find I was getting similar results.
Anything you can offer would be helpful!
Edit:
CREATE TABLE `Table` (
`id` int(11) NOT NULL auto_increment,
`column_a` varchar(32) character set utf8 NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
mysql> SELECT * FROM Table;
+------+----------+
| id | column_a |
+------+----------+
| 1 | asdf |
| 2 | foobar |
+------+----------+
When I call spGetId() with any argument, it returns the value '31' (even if the argument is 'foobar', which should return an integer value of '2' (or ascii 0x32)). If I modify spGetId() to return the total rowcount of Table, instead of returning '2', it returns '32'.
Your stored proc is working. I think it is returning the ascii value of the character '1' instead of the integer value 1.
I need to learn to vary my testing environments.
I'm still not sure exactly what the problem was, but it looks like phpMyAdmin was performing some kind of type conversion of its own, and I had been running all my tests through that particular client.
Throwing together a quick PHP script of my own and manually calling the sproc (and in further testing, calling a stored function as well) provided the desired results.
So, lesson learned: don't ever trust the client. Got to remember to switch it up a bit.

Inserting null into char(1)

I am creating a INSERT script and I am coming across a problem. There is a middle initial field that is a char(1)
Sometimes the records don't have anything in that field so I put a NULL. This causes a Data too long for column error. I don't want to just put ' ' as that leaves just a blanks space.
Is there another way around this?
It sounds like you may be attempting to insert the string 'NULL' into the char(1) field, rather than an SQL NULL, and you have strict SQL mode enabled, which prevents this being truncated to N.
If you are able, run
SHOW CREATE TABLE <your_table_name>
in the MySQL shell to determine whether your target field accepts NULLs. With no context (are you running this as pure SQL, or connecting to the database from some client program in another langauge?) it's difficult to provide the exact solution, but you may have something like this:
INSERT <your_table_name>
SELECT first_name, 'NULL', last_name
where 'NULL' is simply a string with no special meaning, when what you intend is
INSERT <your_table_name>
SELECT first_name, NULL, last_name
Here's an illustration:
mysql> CREATE TABLE my_table ( middle_initial CHAR(1) NULL );
mysql> INSERT INTO my_table SELECT 'NULL';
mysql> SHOW WARNINGS;
Level Code Message
Warning 1265 Data truncated for column 'middle_initial' at row 1
mysql> SELECT * FROM my_table;
middle_initial
--------------
N
mysql> set sql_mode = 'STRICT_TRANS_TABLES';
mysql> INSERT INTO my_table SELECT 'NULL';
ERROR 1406 (22001) at line 16: Data too long for column 'middle_initial' at row 1
mysql> INSERT INTO my_table SELECT NULL;
mysql> SELECT * FROM my_table;
middle_initial
--------------
N
NULL
Bit of a punt - apologies if no use ...